我们在前面的文章"如何遍历QML Item下的所有的children并显示它们的属性"中,已经介绍了如何在QML中寻找自己的children.在今天的例程中,我们将介绍如何在Qt C++代码中遍历一个QML的所有Item,并修改它的属性.
我们的QML程序非常简单,就是源自SDK自带的模版:
Main.qml
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!")
}
}
}
}
}
为了能够实现遍历的工作,我们首先需要把我们的QML中的Item表上自己的objectName.比如上面的"column","label"及"button".这些objectName并不要求是唯一的.比如对于ListView中的delegate来说,如果delegate定义了自己的objectName,那么所有的delegate的实例就都有同样的objectName.
我们的C++代码非常简单:
main.cpp
#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");
我们通过两种不同的方法来设置和读取我们在上面定义objectName为"text"的Label的属性.把它默认的颜色设为红色,并把它的字体的大小设为大.
运行我们的代码:
我们在SDK中的输出为:
Text Property value: "Hello.."
Property value: "medium"
整个项目的源码为: https://github.com/liu-xiao-guo/qmlobject1