Reputation:
I want to change object defined in QML from a slot in C++. In slot startButtonClicked()
I start timer which every second calls slot getData()
. How can I change the label defined in QML from C++ slot genData()
? Now I am able to change in only from main.cpp
class LogicClass : public QObject
{
Q_OBJECT
public:
LogicClass();
~LogicClass();
public slots:
void startButtonClicked(const QVariant &v);
void getData();
};
main:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
class LogicClass logicClass;
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
QObject *rootObject = engine.rootObjects().first();
QObject *qmlObject = rootObject->findChild<QObject*>("startButton");
QObject::connect(qmlObject, SIGNAL(qmlSignal(QVariant)),&logicClass, SLOT(startButtonClicked(QVariant)));
return app.exec();
}
qml:
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
ApplicationWindow {
id: window
objectName: "window"
visible: true
width: 640
height: 520
title: qsTr("MY app")
Button {
id: startButton
objectName: "startButton"
x: 25
text: qsTr("Start")
signal qmlSignal(var anObject)
MouseArea {
anchors.fill: parent
onClicked: startButton.qmlSignal(startButton)
}
}
Label {
objectName: "latitudeLabelValue"
id: latitudeLabelValue
y: 478
width: 50
text: qsTr("")
}
}
}
Upvotes: 1
Views: 138
Reputation:
Passing a pointer to rootObject
to LogicClass()
can be a solution.
QObject *rootObject = engine.rootObjects().first();
class LogicClass logicClass(rootObject);
Save it as a aparameter of a class, and use it. this->rootObject->rootObject->findChild<QObject*>("latitudeLabelValue");
and then the setProperty()
function.
Upvotes: 0
Reputation: 105
You have to use the setProperty
method:
QObject *lblLatitute = rootObject->findChild<QObject*>("latitudeLabelValue");
lblLatitute->setProperty("text", "234.234");
But consider to use the model/view/delegate paradigm.
Upvotes: 1