Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Qt 6 C++ GUI Programming Cookbook - Third Edition

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

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781805122630
Pages 428 pages
Edition 3rd Edition
Languages
Author (1):
Lee Zhi Eng Lee Zhi Eng
Profile icon Lee Zhi Eng

Table of Contents (17) Chapters

Preface 1. Chapter 1: Look-and-Feel Customization with Qt Designer 2. Chapter 2: Event Handling – Signals and Slots 3. Chapter 3: States and Animations with Qt and QML 4. Chapter 4: QPainter and 2D Graphics 5. Chapter 5: OpenGL Implementation 6. Chapter 6: Transitioning from Qt 5 to Qt 6 7. Chapter 7: Using Network and Managing Large Documents 8. Chapter 8: Threading Basics –Asynchronous Programming 9. Chapter 9: Building a Touch Screen Application with Qt 6 10. Chapter 10: JSON Parsing Made Easy 11. Chapter 11: Conversion Library 12. Chapter 12: Accessing Databases with SQL Driver and Qt 13. Chapter 13: Developing Web Applications Using Qt WebEngine 14. Chapter 14: Performance Optimization 15. Index 16. Other Books You May Enjoy

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.

You have been reading a chapter from
Qt 6 C++ GUI Programming Cookbook - Third Edition
Published in: Apr 2024 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}