【发布时间】:2021-03-31 22:48:25
【问题描述】:
我正在尝试做一个简单的任务,例如从 C++ 更改某些 QML 对象的属性(文本:),但我失败了。任何帮助表示赞赏。
我没有收到任何错误,窗口出现了,只是 text 属性没有改变(至少我认为)它应该改变。 有什么我没有做错的吗?!!
我正在尝试的是:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQuickItem>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QString>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlComponent component(&engine, QUrl::fromLocalFile("main.qml"));
QObject *object = component.create();
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QString thisString = "Dr. Perry Cox";
object->setProperty("text", thisString); //<--- tried instead of thisString putting "Dr. ..." but nope.
delete object;
return app.exec();
}
main.qml
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
visible: true
width: 360
height: 360
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
Text {
id: whot
text: ""
anchors.centerIn: parent
font.pixelSize: 20
color: "green"
}
}
【问题讨论】:
-
感谢 Retired Ninja 的链接(就像你的名字顺便说一句),但这正是我开始的地方,我在那里做了示例,并认为我会尝试更改一些其他属性,例如 text(不仅仅是宽度和高度)。也许我有点迟钝,但我无法从文档中学习(在此处插入坏词)。
-
我想如果你没有看到它可能会有所帮助。关于从该链接操纵树深处的对象的警告可能是最好的部分。您尝试做的事情可能不是最好的方法。我们曾经做类似文档中描述的事情并通过名称访问子项,但是为一堆东西分配一个唯一的名称是一件痛苦的事情。一般来说,现在我们只需使用 c++ 提供的属性或信号的绑定来保持 qml 同步,我们会更开心。
-
所以你的意思是我应该深入研究文档,或者是否有任何其他信息来源可以从中学到一些东西?