简体   繁体   中英

Changing QML object from C++ slot

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("")
        }

    }

}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM