[Qt-qml] Accessing dynamic properties

denis.dzyubenko at nokia.com denis.dzyubenko at nokia.com
Tue Sep 14 18:58:21 CEST 2010


On 14. sep. 2010, at 18.20, Hicks Jamey (Nokia-NRC/Cambridge) wrote:

> How did you pass in the object? If you pass it as a QVariant you need to cast it to QObject * first to make its slots and properties available.

I've created a test app that shows the problem. Maybe someone can tell me if this is supposed to work at all:

#include <QtGui>
#include <QtDeclarative>

class MyItem: public QDeclarativeItem
{
    Q_OBJECT
    Q_PROPERTY(int bar READ bar WRITE setBar)

public:
    MyItem()
        : m_bar(69)
    {
        setProperty("foo", QVariant::fromValue<int>(42));
        setProperty("bar", QVariant::fromValue<int>(43));
    }

    int m_bar;
    int bar() const  { return m_bar; }
    void setBar(int value) { m_bar = value; }
};
QML_DECLARE_TYPE(MyItem);

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    qmlRegisterType<MyItem>("org.foobar.foo", 1, 0, "MyItem");
    QDeclarativeView view;

    view.setSource(QUrl::fromLocalFile("foo.qml"));

    view.show();
    return app.exec();
}

#include "main.moc"



and the foo.qml:

import Qt 4.7
import org.foobar.foo 1.0

MyItem {
    width: 100
    height: 100

    MouseArea {
        anchors.fill: parent
        onClicked: { console.log("foo =", parent.foo, "; bar =", parent.bar); }
    }
}


I get the following output:

foo = undefined ; bar = 43

Denis.





More information about the Qt-qml mailing list