QML slot looses context
-
Hello.
I am developing an application with QML frontend and C++ backend - QML retrieves all data required by calling C++ functions on backend. From QML backend functions are accessible through special context property which is set like that:
@
Backend backend;
qmlContext->setContextProperty("backend", &backend);
@This is working nicely. However some backend functions are asynchrounous, so I would like to implement a promise-like solution - asynchronous function would return an intermediate promise object, which would emit signals when data is available. So my Promise class looks like this:
@
class Promise: public QObject
{
Q_OBJECT
public:
explicit Promise(QObject* parent=0);signals:
void finished(QVariant value);private:
Q_DISABLE_COPY(Promise)
...
};...
qmlRegisterUncreatableType<Promise>("com.myapp", 1, 0, "Promise", "Promise can only be created from c++");@
In Backend class asynchronous function is implemented like this:
@
Q_INVOKABLE Promise* getData();
..
Promise* Backend::getData()
{
auto promise = new Promise();
...
return promise;
}@
In QML I am calling backend function, get promise object and connect a javascript function to its signal like this:
@
Item {
id: rootButton { id: button ... onClicked: { promise = backend.getData(); promise.finished.connect(gotData); } } } property var promise: null function gotData() { console.log("gotData", root, button); // prints: gotData undefined undefined }
}
@
The problem is, that QML function is called as intended when promise object emits 'finished' signal, however in that function no context variables are accessible.
Am I missing something? Or is my approach totally wrong?
-
Hi,
Can you try just calling function gotData() directly and see if you get access to those components in it ? Also is the Item with id root inside any other Item ?
-
Yes, if called normally, gotData works as expected. Also tried to connect to a signal on backend object - also worked correctly. Only when connecting on promise signal it does not work as I want
-
Hmm.. Can you post the complete compilable code which shows the problem?
-
Ok, it seems the problem was not with my promise pattern - some other code was simply recreating views, hence lost context. Stupid me :/ Thank you, p3c0