我想从C ++中的一个插槽中更改QML中定义的对象。在插槽startButtonClicked()
中,我启动计时器,每秒调用插槽getData()
。如何从C ++插槽genData()
更改QML中定义的标签?现在我只能从main.cpp
class LogicClass : public QObject
{
Q_OBJECT
public:
LogicClass();
~LogicClass();
public slots:
void startButtonClicked(const QVariant &v);
void getData();
};
主要:
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("")
}
}
}
答案 0 :(得分:1)
您必须使用setProperty
方法:
QObject *lblLatitute = rootObject->findChild<QObject*>("latitudeLabelValue");
lblLatitute->setProperty("text", "234.234");
但考虑使用model / view / delegate范例。
答案 1 :(得分:0)
将指针rootObject
传递给LogicClass()
可以解决问题。
QObject *rootObject = engine.rootObjects().first();
class LogicClass logicClass(rootObject);
将其保存为类的参数,并使用它。 this->rootObject->rootObject->findChild<QObject*>("latitudeLabelValue");
然后是setProperty()
函数。