Communication between C++ and QML

后端 未结 2 1541
鱼传尺愫
鱼传尺愫 2020-12-31 11:27

This page shows how to call C++ functions from within QML.

What I want to do is change the image on a Button via a C++ function (trigger a state-change or however it

2条回答
  •  我在风中等你
    2020-12-31 12:00

    So, you could set your C++ object as a context property on the QDeclarativeView in C++, like so:

    QDeclarativeView canvas;
    ImageChanger i; // this is the class containing the function which should change the image
    canvas.rootContext()->setContextProperty("imgChanger", &i);
    

    In your ImageChanger class, declare a signal like:

    void updateImage(QVariant imgSrc);

    Then when you want to change the image, call emit updateImage(imgSrc);.

    Now in your QML, listen for this signal as follows:

    Image {
        id: imgToUpdate;
    }
    
    Connections {
        target: imgChanger;
        onUpdateImage: {
            imgToUpdate.source = imgSrc;
        }
    }
    

    Hope this helps.

提交回复
热议问题