[Interest] Why is this not working? Assign direct to QML (through setContextProperty) works, as function doesn't.

Mark markg85 at gmail.com
Thu Nov 8 22:19:08 CET 2012


Hi,

Lets take this (pseudo code) as example.
I made a custom QStringListModel class and calles it PathModel:

pathmodel.h
class PathModel : public QStringListModel
{
public:
    explicit PathModel(QObject *parent = 0);
};

Then i made a custom "utils" class where i just make some random
functionality available. Like so:

util.h
class Util : public QObject
{
    Q_OBJECT
public:
....
    Q_INVOKABLE PathModel* pathModel();
    Q_INVOKABLE QString testString() { return "some_test_text"; }
....
};

Then i have the main file where i create the QML context and load a
QML file. Just the default stuff when you make a QML application
through QtCreator. It looks like this:

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));

    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/Porpoise/main.qml"));
    viewer.showExpanded();

    return app->exec();
}

The above helps understanding the context. In the above you can
already see that i want to send the Util class to QML. I do that like
so:

Util util;
viewer.rootContext()->setContextProperty("Util", &util);

Now in QML i call:
Util.testString()
Reply: "some_test_text"

That is es expected. Nothing wrong.

Now if i call:
Util.pathModel()
Reply: undefined

UNDEFINED..! Why?

If i do this:
viewer.rootContext()->setContextProperty("PathModel", Util.pathModel());

and then call it in QML like so:
PathModel
Reply: QStringListModel(0x2072430)

QStringListModel is OK since PathModel inherits from that. So
assigning it directly to QML works, but assigning it through some
other class doesn't. Can anyone tell me why that's the case? And more
importantly, how can i fix this?

Note: i cannot do qRegisterMetaType on the PathModel since it's class
that inherits from a class that forbids copying the data (copy
constructor stuff).

Cheers,
Mark



More information about the Interest mailing list