[Interest] Why is this not working? Assign direct to QML (through setContextProperty) works, as function doesn't.
Tony Rietwyk
tony at rightsoft.com.au
Fri Nov 9 03:36:50 CET 2012
> Sent: Friday, 9 November 2012 8:19 AM
>
> 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
Hi Mark,
Try adding Q_OBJECT to your PathModel - maybe the function doesn't work
because the returned value does not have its own moc object.
Tony.
More information about the Interest
mailing list