Update QML text from C++



  • Hi,

    I have some issues changing the text of a QML window in QT. I have a C++ file that calls a thread and from there I'm trying to change the value of the text label. The thread is running correctly but the text value from the QML is not changing. Below is part of my code:
    === main.cpp ===

    int main(int argc, char *argv[]){
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:///template.qml")));
    
        QQuickItem *label     = engine.rootObjects().at(0)->findChild<QQuickItem*>("myLabel");
        thread2 thread(label);
        thread.start();
    }
    

    === Thread.cpp ===

    thread2::thread2(QQuickItem *label){
        this->label = label;
    }
    
    void thread2::run(){
    
        int test = 0;
        char buffer[10];
        int speed = 100;
    
        while(1){
               speed++;
               sprintf(buffer,"%d km/h",speed);          
               this->label->setProperty("text", QString(buffer));
               QThread::msleep(1000);
               qDebug()<<"tic: "<<buffer<<endl;           
           }
    

    === template.qml ===

    Window {
        id: window
    visible: true
    width: 360
    height: 360
    
    Component {
        id: fruitDelegate
        Row {
            spacing: 10
            Text { text: name }
            Text { text: '$' + cost }
        }
    }
        Text {
            width: 99
            height: 19
            text: qsTr("Speed: ")
                anchors.verticalCenterOffset: 1
                anchors.horizontalCenterOffset: 0
                anchors.centerIn: parent
                objectName: "lab"
        }
        Text {
            width: 38
            height: 19
            text: qsTr(" 0 ")
                anchors.verticalCenterOffset: 1
                anchors.horizontalCenterOffset: 46
                anchors.centerIn: parent
                objectName: "myLabel"
            }
    }
    

    ======================

    Can anyone tell me why is not working? Where is my mistake?

    Thanks!


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Without diving too deep in your code, the first thing that comes to mind is: don't manipulate a GUI element outside of the GUI thread.

    And it should rather be the other way around, make your thread class emit a new value and connect the GUI to that signal. This way you'll avoid a needless tight dependency and make your your code cleaner to maintain.


Log in to reply