QT QML mixed with C++

QML and C++ mixed programming is to use QML to build UI efficiently and conveniently, while C++ is used to implement business logic and complex algorithms.

ML access to C++
Qt integrates the QML engine and the Qt meta-object system, making it easy to extend QML from C++. Under certain conditions, QML can access members of QObject-derived classes, such as signals, slot functions, enumeration types, properties, member functions, etc.

There are two ways for QML to access C++: one is to register the C++ class in the Qt meta object system, and instantiate and access it in QML; the other is to instantiate and set it as a QML context attribute in C++ and use it directly in QML. The first method can make the C++ class as a data type in QML, such as function parameter type or attribute type, or use its enumeration type, singleton, etc., which is more powerful.

For a C++ class to be accessed by QML, two conditions must first be met :

One is derived from the QObject class or a subclass of the QObject class

The second is to use the Q_OBJECT macro.

The QObject class is the base class of all Qt objects. As the core of the Qt object model, it provides many important features such as signal and slot mechanisms. These two conditions are to allow a class to enter the powerful meta-object system of Qt. Only by using the meta-object system, some methods or properties of a class may be called by the name in the form of a string ( ? ? ) , only have the basic conditions for access in QML. 

The Q_OBJECT macro must be declared in the private area of ​​the C++ class (C++ is private by default), used to declare signals and slots, and use the content provided by the Qt meta-object system. The location is generally in the first line of the statement block.


Once you export a class, it is necessary to access the properties or methods of the instance of the class in QML to achieve a certain purpose. What are the characteristics of the properties or methods in the C++ class that can be accessed by QML?

(1) Signal, slot 

As long as it is a signal or a slot, it can be accessed in QML. You can connect the signal of the C++ object to the method defined in QML, you can also connect the signal of the QML object to the slot of the C++ object, and you can directly call the C++ object The slot or signal... So, this is the easiest and easiest way to use it.

(2) Q_INVOKABLE macro 

When defining a member function of a class, use the Q_INVOKABLE macro to decorate, so that the method can be called by the meta-object system. This macro must be placed before the return type.


Program example:

Build Projects, select Qt Quick Application.


Ref:

http://blog.51cto.com/9291927/1975383

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325754175&siteId=291194637