Why would you do that when you have the option to put QObject
s into dedicated threads, execute code without blocking the main thread, and communicate and deliver results back and forth to QML asyncronously?
You don't need WorkerScript
, nor is this its intended use. And since your code is C++ anyway, all you need is QThread
and QObject
.
Here is a simple example:
class Worker : public QObject {
Q_OBJECT
public slots:
void doWork() {
int i = 0;
while (i < 100) {
result(i++);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
signals:
void result(int r);
};
class Controller : public QObject {
Q_OBJECT
public:
Controller() {
w = new Worker;
t = new QThread;
w->moveToThread(t);
connect(this, SIGNAL(start()), w, SLOT(doWork()));
connect(w, SIGNAL(result(int)), this, SIGNAL(result(int)));
t->start();
}
private:
Worker * w;
QThread * t;
signals:
void start();
void result(int r);
};
// in main.cpp
Controller cw;
engine.rootContext()->setContextProperty("Work", &cw);
engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); // load main qml
// QML
Column {
Button {
id: start
onClicked: Work.start()
}
Text {
id: res
}
}
Connections {
target: Work
onResult: res.text = r
}
It is a simple blocking worker that will block its thread for about 50 seconds, but nonetheless will be able to emit results that will be updated on the QML side, while keeping the GUI thread free. Note that once the work function is invoked, it is not possible to interrupt, pause, or control it in any way, if that is required, you will have to implement a non-blocking worker instead. Also not the need of a C++ controller to be present to act as a mediator between QML and the "threaded object", as it seems that QML doesn't get along with such objects directly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…