Exposing the QML object pointer to C++
Sometimes, we want to modify the properties of a QML object through C++ scripting, such as changing the text of a label, hiding/showing the widget, or changing its size. Qt’s QML engine allows you to register your QML objects to C++ types, which automatically exposes all its properties.
How to do it…
We want to create a label in QML and change its text occasionally. To expose the label object to C++, we can do the following:
- Create a C++ class called
MyLabel
that extends from theQObject
class inmylabel.h
:class MyLabel : public QObject { Q_OBJECT public: // Object pointer QObject* myObject; explicit MyLabel(QObject *parent = 0); // Must call Q_INVOKABLE so that this function can be used in QML Q_INVOKABLE void SetMyObject(QObject* obj); }
- In the
mylabel.cpp
source file, define a function calledSetMyObject()
to save the object pointer. This function will later be called in QML inmylabel.cpp
:void MyLabel::SetMyObject(QObject* obj) { // Set the object pointer myObject = obj; }
- In
main.cpp
, include theMyLabel
header and register it to the QML engine using theqmlRegisterType()
function:include "mylabel.h" int main(int argc, char *argv[]) { // Register your class to QML qmlRegisterType<MyLabel>("MyLabelLib", 1, 0, "MyLabel"); }
- Notice that there are four parameters you need to declare in
qmlRegisterType()
. Besides declaring your class name (MyLabel
), you also need to declare your library name (MyLabelLib
) and its version (1.0
). This will be used to import your class into QML. - Map the QML engine to our label object in QML and import the class library we defined earlier in Step 3 by calling
import MyLabelLib 1.0
in our QML file. Notice that the library name and its version number have to match the one you declared inmain.cpp
; otherwise, it will throw an error. After declaringMyLabel
in QML and setting its ID as mylabels, callmylabel.SetMyObject(myLabel)
to expose its pointer to C/C++ right after the label is initialized:import MyLabelLib 1.0 ApplicationWindow { id: mainWindow width: 480 height: 640 MyLabel { id: mylabel } Label { id: helloWorldLabel text: qsTr("Hello World!") Component.onCompleted: { mylabel.SetMyObject(hellowWorldLabel); } } }
- Wait until the label is fully initiated before exposing its pointer to C/C++; otherwise, you may cause the program to crash. To make sure it’s fully initiated, call the
SetMyObject()
function withinComponent.onCompleted
and not in any other functions or event callbacks. Now that the QML label has been exposed to C/C++, we can change any of its properties by calling thesetProperty()
function. For instance, we can set its visibility totrue
and change its text toBye
bye world!
:// Qvariant automatically detects your data type myObject->setProperty("visible", Qvariant(true)); myObject->setProperty("text", Qvariant("Bye bye world!"));
- Besides changing the properties, we can also call its functions by calling the following code:
QVariant returnedValue; QVariant message = "Hello world!"; QMetaObject::invokeMethod(myObject, "myQMLFunction", Q_RETURN_ARG(QVariant, returnedValue), Q_ARG(QVariant, message)); qDebug() << "QML function returned:" << returnedValue.toString();
- Or, simply, we can call the
invokedMethod()
function with only two parameters if we do not expect any values to be returned from it:QMetaObject::invokeMethod(myObject, "myQMLFunction");
How it works…
QML is designed in such a way that it can be expanded through C++ code. The classes in the Qt QML module permit QML objects to be used and operate from C++, and the capability of the QML engine united with Qt’s meta-object system allows C++ functionality to be called directly from QML. To add some C++ data or usage to QML, it should come forward from a QObject-derived class. QML object types could be instituted from C++ and supervised to access their properties, appeal their methods, and get their signal alerts. This is possible because all QML object types are executed using QObject-derived classes, allowing the QML engine to forcibly load and inspect objects through the Qt meta-object system.
There’s more…
Qt 6 comes with two different types of GUI kits – Qt Widgets and Qt Quick. Both have their strengths and advantages over the other, giving programmers the ability and freedom to design their application’s interface without having to worry about feature constraints and performance issues.
Qt 6 allows you to pick the best method and programming language that suits your working style and requirements for your project. By going through this chapter, you will be able to create a good-looking and functional cross-platform application using Qt 6 in no time.