QQuickWidget and C++ interaction
Asked Answered
U

1

8

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?

Unpolite answered 28/5, 2014 at 13:13 Comment(0)
F
4

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.

Finbur answered 28/5, 2014 at 13:43 Comment(1)
don't see the reason why setContextProperty("test", 0) doesn't work as well as setContextProperty("test", "some random text")Finbur

© 2022 - 2024 — McMap. All rights reserved.