Communication between C++ and QML

后端 未结 2 1520
鱼传尺愫
鱼传尺愫 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 11:56

    If you set an objectName for the image, you can access it from C++ quite easy:

    main.qml

    import QtQuick 1.0
    
    Rectangle {
        height: 100; width: 100
    
        Image {
            objectName: "theImage"
        }
    }
    

    in C++:

    // [...]
    
    QDeclarativeView view(QUrl("main.qml"));
    view.show();
    
    // get root object
    QObject *rootObject = dynamic_cast<QObject *>(view.rootObject());
    
    // find element by name
    QObject *image = rootObject->findChild<QObject *>(QString("theImage"));
    
    if (image) { // element found
        image->setProperty("source", QString("path/to/image"));
    } else {
        qDebug() << "'theImage' not found";
    }
    
    // [...]
    

    → QObject.findChild(), QObject.setProperty()

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题