QML 中拥有的对象组件对象、对象属性,方法,信号

组件对象

  1. QObject *obj = engine.rootObjects().first();
  2. QObject *listView = obj->findChild<QObject*>("listView");

对象属性

  1. // 访问和修改属性值有多种方法,但记住以下这条就够了
  2. obj->setProperty("width", 300);
  3. qDebug() << obj->property("width").toInt() << endl;

以下的做法不建议,因为绕过了强大的元对象系统,QML 引擎无法意识到属性值的更改。
(本来我以为更好,因为代码有提示)

  1. QObject *obj = engine.rootObjects().first();
  2. QQuickWindow *win = static_cast<QQuickWindow*>(obj);
  3. win->setWidth(300);
  4. qDebug() << win->width() << endl;

对象方法

在 C++ 中通过 QMetaObject::invokeMethod() 来调用 QML 中的方法,参数和返回值都转换为 QVariant 类型。

  1. // QML 中的方法
  2. Item {
  3. function qmlFunc(msg) {
  4. console.log(msg)
  5. return "from qml"
  6. }
  7. }
  8. // C++ 中调用
  9. QVariant retVal;
  10. QVariant argVal = "from cpp";
  11. QMetaObject::invokeMethod(
  12. obj, "qmlFunc",
  13. Q_RETURN_ARG(QVariant, retVal), Q_ARG(QVariant, argVal));

信号

  1. // QML
  2. signal qmlSignal(string msg)
  3. MouseArea {
  4. anchors.fill: parent
  5. // 点击鼠标,发射信号
  6. onClicked: item.qmlSignal("from qmlSignal!")
  7. }
  8. // C++
  9. connect(qmlObj, SIGNAL(qmlSignal(QString)), &cppObj, SLOT(cppSlot(QString)));

参数类型,当 qml 的参数类型为 string 时,在 C++ 中需写成 QString;
当 qml 的参数类型是对象类型时,在 qml 中写成 var 类型,在 C++ 中写成 QVariant 类型。