[英]Changing QML object from C++ slot
I want to change object defined in QML from a slot in C++. 我想从C ++中的插槽更改QML中定义的对象。 In slot
startButtonClicked()
I start timer which every second calls slot getData()
. 在插槽
startButtonClicked()
我启动计时器,每秒钟调用一次插槽getData()
。 How can I change the label defined in QML from C++ slot genData()
? 如何从C ++插槽
genData()
更改QML中定义的标签? Now I am able to change in only from main.cpp 现在我只能从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: 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("")
}
}
}
You have to use the setProperty
method: 您必须使用
setProperty
方法:
QObject *lblLatitute = rootObject->findChild<QObject*>("latitudeLabelValue");
lblLatitute->setProperty("text", "234.234");
But consider to use the model/view/delegate paradigm. 但是请考虑使用模型/视图/委托范式。
Passing a pointer to rootObject
to LogicClass()
can be a solution. 将指向
rootObject
的指针传递给LogicClass()
可能是一种解决方案。
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. 然后是
setProperty()
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.