11
votes

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 is done).

How can I achieve this?

UPDATE

I tried the approach by Radon, but immediately when I insert this line:

    QObject *test = dynamic_cast<QObject *>(viewer.rootObject());

Compiler complains like this:

    error: cannot dynamic_cast '((QMLCppBinder*)this)->QMLCppBinder::viewer.QDeclarativeView::rootObject()' (of type 'struct QGraphicsObject*') to type 'class QObject*' (source is a pointer to incomplete type)

In case it is relevant, QMLCppBinder is a class that I try to build to encapsulate the connections from several QML pages to C++ code. Which seems to be trickier than one might expect.

Here is a skeleton class to give some context for this:

    class QMLCppBinder : public QObject
    {
        Q_OBJECT
    public:
        QDeclarativeView viewer;

        QMLCppBinder() {
            viewer.setSource(QUrl("qml/Connect/main.qml"));
            viewer.showFullScreen();
            // ERROR
            QObject *test = dynamic_cast<QObject *>(viewer.rootObject());
        }
    }
2
the "error: cannot dynamic_cast" was probably caused by a missing header include "#include <QGraphicsObject>" if anyone comes across this.Andrew

2 Answers

15
votes

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

5
votes

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.