Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between C++ and QML

Tags:

c++

qt

qml

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());
        }
    }
like image 410
Hedge Avatar asked Apr 18 '11 23:04

Hedge


2 Answers

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

like image 188
hiddenbit Avatar answered Nov 11 '22 01:11

hiddenbit


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.

like image 37
funkybro Avatar answered Nov 11 '22 02:11

funkybro