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: root
Button {
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?
↧










