Reader small image

You're reading from  Qt 6 C++ GUI Programming Cookbook - Third Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805122630
Edition3rd Edition
Right arrow
Author (1)
Lee Zhi Eng
Lee Zhi Eng
author image
Lee Zhi Eng

Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine. He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.
Read more about Lee Zhi Eng

Right arrow

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:

  1. Create a C++ class called MyLabel that extends from the QObject class in mylabel.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);
    }
  2. In the mylabel.cpp source file, define a function called SetMyObject() to save the object pointer. This function will later be called in QML in mylabel.cpp:
    void MyLabel::SetMyObject(QObject* obj) {
         // Set the object pointer
         myObject = obj;
    }
  3. In main.cpp, include the MyLabel header and register it to the QML engine using the qmlRegisterType() function:
    include "mylabel.h"
    int main(int argc, char *argv[]) {
         // Register your class to QML
         qmlRegisterType<MyLabel>("MyLabelLib", 1, 0, "MyLabel");
    }
  4. 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.
  5. 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 in main.cpp; otherwise, it will throw an error. After declaring MyLabel in QML and setting its ID as mylabels, call mylabel.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);
               }
         }
    }
  6. 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 within Component.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 the setProperty() function. For instance, we can set its visibility to true and change its text to Bye bye world!:
    // Qvariant automatically detects your data type
    myObject->setProperty("visible", Qvariant(true));
    myObject->setProperty("text", Qvariant("Bye bye world!"));
  7. 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();
  8. 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.

Previous PageNext Chapter
You have been reading a chapter from
Qt 6 C++ GUI Programming Cookbook - Third Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805122630
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Lee Zhi Eng

Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine. He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.
Read more about Lee Zhi Eng