// Declare a C++ class class MyClass : public QObject { Q_OBJECT public: Q_INVOKABLE void doSomething() { ... } }; // Create an instance of the class MyClass myObj; // Set up the QmlApplicationViewer QmlApplicationViewer viewer; viewer.rootContext()->setContextProperty("myObj", &myObj); // Use the object in QML Button { onClicked: myObj.doSomething() }
// Declare a C++ class with a property class MyModel : public QObject { Q_OBJECT Q_PROPERTY(int count READ count NOTIFY countChanged) public: int count() const { return m_count; } void setCount(int count) { if (count != m_count) { m_count = count; emit countChanged(); } } signals: void countChanged(); private: int m_count; }; // Create an instance of the class MyModel myModel; // Set up the QmlApplicationViewer QmlApplicationViewer viewer; viewer.rootContext()->setContextProperty("myModel", &myModel); // Use the property in QML Text { text: "Count: " + myModel.count }In this example, we create a C++ class called MyModel and expose a property called count to QML. We use the Q_PROPERTY macro to declare the property and define a getter and setter for it. We then set up the rootContext to expose an instance of the class to QML and use the count property in a Text element. Package library: Qt