PDA

View Full Version : C++ pointer to Qml - is this possible?!?



Szyk
16th May 2017, 18:42
Hi

[[[ I waste half day for googling and trying different code. So I am not lazy when I am asking. ]]]

I have simple question whether is this possible:
Create and feed QSqlQueryModel in C++ and send it (whatever way) to Qml?
If you claim yes, then please attach prof code...

And I am not interested with expose some alone object to Qt (I have no problem with this - I can use lEngine.rootContext()->setContextProperty from main()) But I want send any number of C++ models to Qml (different models to different Qml objects).
I have problem with passing parameters to functions and to property (pointers as parameters).

Thank you and best regards
Szyk Cech

high_flyer
16th May 2017, 22:30
I admit that QML is not my strong point.
However, since you want to expose a C++ pointer to QML, I don't know if there is any other option but to expose it via a Q_PROPERTY.
So you will have some sort of a C++ QObject class that has a property which is your model pointer and then:


class MyModelExposer : public QObject
{
....
Q_PROPETRY(QSqlQueryModel* sqlQueryModel read sqlQueryModel write setSqlQueryModel NOTIFY onSqlQueryModelChnaged)
...

pivate:
QSqlQueryModel* sqlQueryModel;
};


//Somewhere in your C++ code:
qmlRegisterUncreatableType<MyModelExposer>("bar.foo", 1, 0, "MyModelExposer", "");
...

MyModelExposer modelExposerInstance;
...
..

engine.rootContext()->setContextProperty("modelExposer", &modelExposerInstance);



And then in QML:



SomeModelConsumer {
model: modelExposer.model
}


Again, may be there are sothers here who are better at QML and can offer a better solution and/or correct my answer if it needs correction.

Szyk
17th May 2017, 18:41
You won't notice my mention about setContextProperty... So I am not satisfy with your answer.
Correct answer is that: Yes this is possible in that way:
In order to use pointers variable in Qml you will have to do following steps:
1. Register your class in order to make it understandable to QVariant:
qRegisterMetaType<QSqlQueryModel*>("QSqlQueryModel*");
2. Register your class in Qml:
qmlRegisterType<QSqlQueryModel>("com.shomething", 1, 0, "QSqlQueryModel");
3. Create your variable:
QmlTableModel* lModel2 = new QmlTableModel(this);
4. Get object contains your QSqlQueryModel* property from QQmlApplicationEngine:
QObject* lCallbackObject = findObject(lCallbackObjectName);
5. Set property:
lCallbackObject->setProperty("mModel", QVariant::fromValue(lModel2));

Essential in this procedure is QVariant::fromValue - qVariantFromValue will not work.
I didn't check whether the same works with function calls from C++ to Qml, but it should.