I need to Start immediately and stop then a QThread extended class from Qml File. Is there any solution for that? here is my class :
class SerialManager : publi
Yes, you can expose an instance to QML using setContextProperty (read this document) and then call any method you want by marking it with Q_INVOKABLE. As start() and quit() are slots you don't even need to define those yourself. Something like this should work:
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread() : m_quit(false) {}
Q_INVOKABLE void quit() {
m_quit = true;
}
protected:
void run() {
while (!m_quit)
qDebug("Looping...");
}
private:
volatile bool m_quit;
};
when starting:
MyThread t;
QQuickView view;
[...]
view.engine()->rootContext()->setContextProperty("thread", &t);
In your QML:
thread.start()
or
thread.quit()
if you have SerialManager like this:
class SerialManager : public QThread
{
Q_OBJECT
public:
CircularList<unsigned char> buffer_[2];
signals:
void dataReady(short *value,int len,unsigned short sample);
protected:
void run();
};
in main.cpp add bellow code:
qmlRegisterType<SerialManager>("Device",1,0,"Serial");
then in your qml do this:
Component.onCompleted: {
thread.start()
}
Component.onDestruction:
{
thread.quit()
}
As an alternative solution, more QML oriented, you can export a class of utilities to do your job from C++ to QML, then use a WorkerScript
(see here the documentation) to spawn a new thread and execute a bunch of JavaScript code that deal with that class.
WorkerScript
are meant so that you can:
Use WorkerScript to run operations in a new thread. This is useful for running operations in the background so that the main GUI thread is not blocked.
It would be cleaner and you'd avoid to deal with an annoying start
method from within QML.