Quantcast
Channel: Qt DevNet forums: Qt Quick 1283365070**
Viewing all articles
Browse latest Browse all 4972

How do I actually execute C++ code in Qt Quick?

$
0
0
Ok I think in your case this is the simplest way you ca do it: 1. create a QObject class with your functions and properties, what you want to use from QML, I have created a class claled MyStuff containing a single function “toPigLatin” for this example: class MyStuff : public QObject {     Q_OBJECT public:     explicit MyStuff(QObject *parent = 0) : QObject(parent) {}       Q_INVOKABLE QString toPigLatin(const QString &s) {         return s.mid(1) + s.left(1) + "ay";     } }; you can simply call that function from QML like any other QML function, see below. The function need to be a Qt slot or use the Qt macro Q_INVOKABLE to make it accessible from QML or other scripting languages. 2. in your main.cpp create an Object of the MyStuff class and register the object as the QML context object, there are other ways like I said in an earlier post but in your case this might be the simplest way:     QtQuick2ApplicationViewer viewer; // you should already have this in your main.cpp     MyStuff myStuff;     viewer.rootContext()->setContextObject(&myStuff); that is all, now you can use the function toPigLatin like any global function from anyway in your QML project, e.g.: Rectangle {     width: 360     height: 360       MouseArea {         anchors.fill: parent         onClicked: console.log(toPigLatin("banana"))     } } that is just the hello world QML code, only changed the onClicked slot to a console log, as you can see it calls the c++ function toPigLatin there. :) In the c++ side of the function you can do whatever you like, keep in mind the input and output parameters to QML will be converted by the QML engine, so you should use compatible types like QString and not std:.string, that won’t work here (unless you provide a custom conversion from and to JavaScript). If you need to use a std:.string internally you can just convert the QString to a std::string with QString::toStdString(), but in your case I think QString is the better choice anyways. :)

Viewing all articles
Browse latest Browse all 4972

Trending Articles