Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QQuickWidget and C++ interaction

I am experiencing with the new QQuickWidget. How can I interact between the QQuickWidget and C++?

C++

QQuickWidget *view = new QQuickWidget();
view->setSource(QUrl::fromLocalFile("myqml.qml"));
view->setProperty("test", 0);

myLayout->addWidget(view);

QML

import QtQuick 2.1

Rectangle {
    id: mainWindow
    width: parent.width
    height: parent.height

    Text {
        id: text
        width: mainWindow.width
        font.pixelSize: 20
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        text: test
    }
}

text: test does not work: ReferenceError: test is not defined

How can I give my QML file some properties via C++?

Is it also possible to get the Text object in C++ and update its text?

like image 484
Niklas Avatar asked May 28 '14 13:05

Niklas


1 Answers

Give it a try:

view->rootContext()->setContextProperty("test", "some random text");

instead of

view->setProperty("test", 0);

setProperty(name, val) works if object has the property name defined as Q_PROPERTY.

It is possible to pass QObject-derived object as view's context property:

class Controller : public QObject
{
    Q_OBJECT
    QString m_test;

public:
    explicit Controller(QObject *parent = 0);

    Q_PROPERTY(QString test READ test WRITE setTest NOTIFY testChanged)

    QDate test() const
    {
        return m_test;
    }

signals:

    void testChanged(QString arg);

public slots:

    void setTest(QDate arg)
    {
        if (m_test != arg) {
            m_test = arg;
            emit testChanged(arg);
        }
    }
};

Controller c;
view->rootContext()->setContextProperty("controller", &c);

Text {
        id: text
        width: mainWindow.width
        font.pixelSize: 20
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        text: controller.test
    }

Is it also possible to get the Text object in C++ and update its text?

In general, it doesn't seem to be the best approach -- c++ code shouldn't be aware of presentation if it follows model-view pattern.

However it is possible as described here.

like image 118
Evgeny Timoshenko Avatar answered Sep 19 '22 17:09

Evgeny Timoshenko