目录
Qml 接收 C++ 对象信号
- 在main.cpp
qmlRegisterType<TestCpp>("com.testcompany.qmlcomponents", 1, 0, "TestCpp");
- C++ 属性的操作函数,加上触发信号:
- testcpp.cpp
void TestCpp::setNumber(int number) { m_iNumber += number; emit numberChanged(); }
- main.qml
import QtQuick 2.12 import QtQuick.Controls 2.5 import com.testcompany.qmlcomponents 1.0 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("QmlTest") TestCpp{ id: testcpp number: 666 onNumberChanged: { btn1.text = testcpp.number } } Button{ id: btn1 width: 120 height: 50 anchors.centerIn: parent onClicked: { text = testcpp.number; } } Button{ id: btn2 width: 120 height: 50 anchors.top: btn1.bottom anchors.margins: 15 anchors.horizontalCenter: btn1.horizontalCenter onClicked:{ testcpp.setNumber(100) } } }
- 效果
C++ 调用 Qml 对象槽函数
- main.cpp
- 使用 engine.rootContext()->setContextProperty 的方式注册 C++ 类的实例对象,这样可以直接使用信号槽。
TestCpp testcpp; testcpp.setNumber(12345); engine.rootContext()->setContextProperty("testcpp", &testcpp);
- 通过QQmlComponent 创建组件的代码
QObject::connect(&testCpp, SIGNAL(valueChanged()), qmlWindows, SLOT(addData()));
- 实例:
- main.cpp
- TestQml.qml
import QtQuick 2.12 import QtQuick.Controls 2.2 import QtQuick.Window 2.2 Window { width: 300 height: 300 color: "red" function addData(){ rect.color = "yellow" } Rectangle{ id:rect objectName: "rectangle" height: 40 width: 40 anchors.centerIn: parent color: "blue" } }
- main.qml
- 属性值的改变触发了valueChanged 信号, Qml 端的 function 就被触发修改了颜色.
C++ 访问 Qml 对象属性
QObject *qmlRect = qmlTest->findChild<QObject*>("rectangle"); qmlRect->setProperty("color", "pink");
C++ 调用 Qml 对象公共函数 QMetaObject::invokeMethod
- C++ 直接调用 Qml 对象的公共函数,需要用到 QMetaObject::invokeMethod。
- main.cpp
QMetaObject::invokeMethod(qmlTest, "addData");
- 执行 qmlTest的 addData 函数。
C++ 接收 Qml 对象信号
- testcpp.h
public slots: void setColor();
- testcpp.cpp
void TestCpp::setColor() { emit numberChanged(); }
- TestQml.qml
import QtQuick 2.12 import QtQuick.Controls 2.2 import QtQuick.Window 2.2 Window { width: 300 height: 300 color: "red" signal numberSignal() function addData(){ rect.color = "pink" } Rectangle{ id:rect objectName: "rectangle" height: 40 width: 40 anchors.centerIn: parent color: "blue" } Button{ id: button width: 120 height: 50 anchors.top: rect.bottom anchors.margins: 15 anchors.horizontalCenter: rect.horizontalCenter onClicked:{ emit: numberSignal() } } }
- main.cpp
QObject::connect(&testcpp, SIGNAL(numberChanged()), qmlTest, SLOT(addData())); QObject::connect(qmlTest, SIGNAL(numberSignal()), &testcpp, SLOT(setColor()));
- Qml 端的 valueChanged 信号触发了 C++ 端的 setColor 槽函数,然后 setColor 槽函数又触发了 Qml 端的 addData 公共函数(可以理解为槽函数),然后颜色值被成功修改.