QML 中拥有的对象组件对象、对象属性,方法,信号
组件对象
QObject *obj = engine.rootObjects().first();QObject *listView = obj->findChild<QObject*>("listView");
对象属性
// 访问和修改属性值有多种方法,但记住以下这条就够了obj->setProperty("width", 300);qDebug() << obj->property("width").toInt() << endl;
以下的做法不建议,因为绕过了强大的元对象系统,QML 引擎无法意识到属性值的更改。
(本来我以为更好,因为代码有提示)
QObject *obj = engine.rootObjects().first();QQuickWindow *win = static_cast<QQuickWindow*>(obj);win->setWidth(300);qDebug() << win->width() << endl;
对象方法
在 C++ 中通过 QMetaObject::invokeMethod() 来调用 QML 中的方法,参数和返回值都转换为 QVariant 类型。
// QML 中的方法Item {function qmlFunc(msg) {console.log(msg)return "from qml"}}// C++ 中调用QVariant retVal;QVariant argVal = "from cpp";QMetaObject::invokeMethod(obj, "qmlFunc",Q_RETURN_ARG(QVariant, retVal), Q_ARG(QVariant, argVal));
信号
// QMLsignal qmlSignal(string msg)MouseArea {anchors.fill: parent// 点击鼠标,发射信号onClicked: item.qmlSignal("from qmlSignal!")}// C++connect(qmlObj, SIGNAL(qmlSignal(QString)), &cppObj, SLOT(cppSlot(QString)));
参数类型,当 qml 的参数类型为 string 时,在 C++ 中需写成 QString;
当 qml 的参数类型是对象类型时,在 qml 中写成 var 类型,在 C++ 中写成 QVariant 类型。
