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)));新闻热点
疑难解答
图片精选