Je suis nouveau sur Qt et j'essaie de modifier un texte QML (affiché à l'écran) à partir du code C++. Je reçois le texte modifié mais il n'est pas mis à jour sur l'écran, donc j'ai la variable texte modifiée mais le premier texte à l'écran.Comment modifier un texte QML à partir de C++
Voici le code:
//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
}
}
Quelqu'un pourrait-il me aider?
Merci.
Avez-vous essayé d'appeler la mise à jour() sur l'élément? En outre, exporter le texte en tant que propriété d'un QObject C++ vers QML (setContextProperty sur le QDeclarativeContext, puis simplement "object.propertyname" dans QML) peut être plus facile. –
Il n'y a pas d'appel de mise à jour() sur l'objet texte. Je vais essayer d'exporter de la façon dont vous me l'avez dit et je vais vous le dire. Merci! – AZorrozua
Essayez de diffuser vers QGraphicsObject au lieu de QObject. –