我们在前面的文章"如何遍历QML Item下的所有的children并显示它们的属性"中,已经介绍了如何在QML中寻找自己的children.在今天的例程中,我们将介绍如何在Qt C++代码中遍历一个QML的所有Item,并修改它的属性.
我们的QML程序非常简单,就是源自SDK自带的模版:
import QtQuick 2.0 import Ubuntu.Components 1.1 /*! \brief MainView with a Label and Button elements. */ MainView { // objectName for functional testing purposes (autopilot-qt5) objectName: "mainView" // Note! applicationName needs to match the "name" field of the click manifest applicationName: "qmlobject1.liu-xiao-guo" /* This property enables the application to change orientation when the device is rotated. The default is false. */ //automaticOrientation: true // Removes the old toolbar and enables new features of the new header. useDeprecatedToolbar: false width: units.gu(60) height: units.gu(85) Page { id: page title: i18n.tr("qmlobject1") Column { objectName: "column" spacing: units.gu(5) anchors { margins: units.gu(2) fill: parent } Label { id: label objectName: "label" text: i18n.tr("Hello..") } Button { objectName: "button" width: parent.width text: i18n.tr("Tap me!") onClicked: { label.text = i18n.tr("..world!") } } } } }
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include <QQuickItem> #include <QQmlProperty> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQuickView view; view.setSource(QUrl(QStringLiteral("qrc:///Main.qml"))); view.setResizeMode(QQuickView::SizeRootObjectToView); QQuickItem* root = view.rootObject(); QObject *object = root->findChild<QObject*>("label"); if (object) { object->setProperty("color", "red"); } qDebug() << "Text Property value:" << QQmlProperty::read(object, "text").toString(); QQmlProperty::write(object, "text", "Good morning"); qDebug() << "Property value:" << object->property("fontSize").toString(); object->setProperty("fontSize", "large"); view.show(); return app.exec(); }
if (object) { object->setProperty("color", "red"); } qDebug() << "Text Property value:" << QQmlProperty::read(object, "text").toString(); QQmlProperty::write(object, "text", "Good morning"); qDebug() << "Property value:" << object->property("fontSize").toString(); object->setProperty("fontSize", "large");
Text Property value: "Hello.." Property value: "medium"