T QObject::findChild(const QString &name = QString(), Qt::FindChildOptionsoptions = Qt::FindChildrenRecursively) const 是一個QObject類型的模板函數,意味著可以轉成任意類型如:
QPushButton* button = root.findChild<QPushButton*>("qml_button")
QObject* object = root.findChild<QObject*>("qml_object")
QQuickItem* item = root.findChild<QQuickItem*>("qml_item")
如果有多個對象使用objectName:"qml_button"同名標記,QObject::findChild返回最后一個標記的QML對象,QObject::findChildren返回所有標記的QML對象存放在QList類型的列表中。例子:QQuickView view; //QQuickView對象view.setSource( QUrl(QStringLiteral("qrc:///main.qml"))); //加載QMLview.show(); //QQuickView可以顯示可視化QML對象QQuickItem* root = view.rootObject(); //返回當前QQuickView的根節點,底下可以綁定很多節點 //在根節點root中查找有objectName:"qml_button"這個標志位保存的QML節點qml_ButtonQObject* button = root->findChild<QObject*>("qml_button"); button->setProperty("width", 500); //在根節點root中查找有objectName:"qml_item"這個標志位保存的QML節點qml_item,換成QQuickItem*類型QQuickItem* item = root->findChild<QQuickItem*>("qml_item"); item->setProperty("color", "red");3、使用C++訪問QML對象成員(1)所有的QML對象都會暴露在Qt的元對象系統,C++可以通過元對象系統的QMetaObject::invokeMethod()調用QML中注冊到元對象系統函數。例子:qml中定義的函數:function qmlFunction(msg){ console.log("QML get message:",msg);}C++調用QML函數:QQmlEngine engine; //QML引擎QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:///main.qml"))); //加載QMLQObject* object = component.create(); //用QQmlComponent創建一個組件的實例,并且賦值給object*,這步操作非常關鍵,Object類型可以轉換其他任意類型,比如QQuickItemQVariant rValue;QVariant msg = "Hello for C++";QMetaObject::invokeMethod(object, "qmlFunction", Q_RETURN_ARG(QVariant,rValue), Q_ARG(QVariant, msg));(2)C++可以接收所有的QML信號,QML也可以接收C++信號,在C++中可以使QObject::connect()進行接收信號槽。例子:qml中定義一個信號:signal qmlSignal(string msg)C++進行連接信號:QQuickView view; //QQuickView對象view.setSource( QUrl(QStringLiteral("qrc:///main.qml"))); //加載QMLview.show(); //QQuickView可以顯示可視化QML對象QQuickItem* root = view.rootObject(); //返回當前QQuickView的根節點,底下可以綁定很多節點QObject::connect(root, SIGNAL(qmlSignal(QString)), this, SLOT(Slotqml(QString)));新聞熱點
疑難解答
圖片精選