How Start a Qthread from qml?

前端 未结 3 721
误落风尘
误落风尘 2021-01-21 18:26

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         


        
3条回答
  •  长情又很酷
    2021-01-21 18:45

    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()
    

提交回复
热议问题