QML与C++交互分为四步:
C++类
先继承QObject创建一个类,添加信号槽
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #ifndef PERSON_H #define PERSON_H
#include <QObject>
class Person : public QObject { Q_OBJECT public: explicit Person(QObject *parent = nullptr) : QObject(parent), m_name(""), m_age(0) {}
QString getName() const { return m_name; } void setName(const QString& name) { m_name = name; emit nameChanged(); }
int getAge() const { return m_age; } void setAge(int age) { m_age = age; emit ageChanged(); }
signals: void nameChanged(); void ageChanged();
private: QString m_name; int m_age; };
#endif
|
Q_PROPERTY
在Q_OBJECT下添加Q_PROPERTY然后QML才能调用。
1 2 3 4
| Q_OBJECT
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged) Q_PROPERTY(int age READ getAge WRITE setAge NOTIFY ageChanged)
|
注册类
上下文注入
1 2 3 4 5 6 7
| Person person;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("person", &person);
|
qmlRegisterType
1 2
| qmlRegisterType<Person>("com.example", 1, 0, "Person");
|
调用类
在qml文件中调用类
上下文注入
如果类是以上下文注入的方式使用,那么对象名就是qml中使用的方式。
调用person的age获取/赋值,类中的具体调用由Q_PROPERTY实现。
1 2 3 4 5 6
| Slider { from: 0 to: 100 value: person.age onValueChanged: person.age = value }
|
qmlRegisterType
如果想捕获C++类的信号,需要先import类,类名就是Person
1 2 3 4 5 6 7 8 9 10 11 12 13
| import com.example 1.0
Connections { target: Person onNameChanged: console.log("Received nameChanged from C++") }
Person { id: person onNameChanged: console.log("Received nameChanged from C++") }
|