3
我是Qt新手,我试图从C++代码修改QML文本(显示在屏幕上)。 我得到的文本被修改,但它并没有在屏幕上更新,所以我有文本变量修改,但屏幕上的第一个文本。如何从C++修改QML文本
下面是代码:
//main.cpp
#include <QApplication>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <QDebug>
#include "qmlapplicationviewer.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
QmlApplicationViewer viewer;
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/textModification/main.qml"));
viewer.showExpanded();
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile("qml/textModification/main.qml"));
QObject *object = component.create();
QObject *item = qobject_cast<QDeclarativeItem*>(object);
QObject *text = item->findChild<QObject*>("text1");
qDebug() << "Text of 'text1' when it's created' -------->" << text->property("text");
text->setProperty("text", "THIS WORKS!");
qDebug() << "Text of 'text1' after modifying it -------->" << text->property("text");
return app->exec();
}
//main.qml
import QtQuick 1.0
Item {
id: item1
objectName: "item1"
width: 400
height: 400
Text {
id: text1
objectName: "text1"
x: 0
y: 0
width: 400
height: 29
text: "This text should change..."
font.pixelSize: 12
}
}
有人能帮助我吗?
谢谢。
你尝试在项目调用update()?此外,将文本作为C++ QObject的属性导出为QML(QDeclarativeContext上的setContextProperty,然后QML中的“object.propertyname”)可能会更容易。 – 2012-01-30 11:48:58
文本对象上没有update()调用。 我会尽力以你告诉我的方式出口,我会告诉你。 谢谢! – AZorrozua 2012-01-30 11:59:29
尝试转换为QGraphicsObject而不是QObject。 – 2012-01-30 12:25:52