Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to set the properties of child from main(Qml/C++)



  • I am new to Qt. I am trying to enable and disable the image from main window with 2 seconds delay but always it is always taking the last property which i implemented. Please find my sample code below. It could be great help if you could provide the solution asap.

    main.cpp

    int main(int argc, char *argv[])
    {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    QObject *object = engine.rootObjects().first();
    
    QObject *test= object->findChild<QObject*>("image");
    
    if(test)
    {
        QThread::msleep(2000);
    
        QQmlProperty::write(test, "visible", "false");
       QThread::msleep(2000);
    
        QQmlProperty::write(test, "visible", "true");
        QThread::msleep(2000);
    
        QQmlProperty::write(test, "visible", "false");
        QThread::msleep(2000);
    
        QQmlProperty::write(test, "visible", "true");
    

    }
    return app.exec();
    }

    main.qml
    import QtQuick 2.9
    import QtQuick.Window 2.2

    Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Test")

    TestForm{}
    }
    TestForm.ui.qml

    import QtQuick 2.4

    Item {
    width: 400
    height: 400

    Image {
        id: image
        x: 67
        y: 98
        width: 100
        height: 100
        source: "test.png"
        objectName: "test"
    }
    

    }


  • Qt Champions 2017

    Avoid placing the sleep. Since you are placing sleep, your screen is getting chance to refresh itself. If you want to check like this, use QTimer & try updating the property every 2 seconds & then check.



  • @dheerendra Thanks for your input. I have tested with timer long back and it is working fine. My actual requirement is Qt will run in one thread and input for Qt will run in another thread and it will cyclicly enable or disable the image based on the user input. When i call cyclic from another thread with user input to display the image and it is not enabled based on the input. this is just an example why it is not updating the data when i call continuously. When we toggle through timer it is working if I call with sequenctially with delay it is not working. May i know the reason?


  • Qt Champions 2017

    Are you using signals/slots across thread for communication ?



  • @dheerendra Yes, I am using signals and slots. post the signals from one thread and implemented the slots in Qt thread. having the same problem. Why it is not working when we give QQmlProperty::write(test, "visible", "false"); and QQmlProperty::write(test, "visible", "true"); continuously. why it is taking always the last option.


Log in to reply