如何从 qml 启动一个 Qthread?

How Start a Qthread from qml?

我需要立即启动并停止,然后从 Qml 文件扩展 class QThread。 有什么解决办法吗? 这是我的 class :

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

是的,您可以使用 setContextProperty(阅读本文档)向 QML 公开一个实例,然后通过使用 Q_INVOKABLE 标记来调用您想要的任何方法。由于 start() 和 quit() 是插槽,您甚至不需要自己定义它们。这样的事情应该有效:

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;
};

开始时:

MyThread t;
QQuickView view;
[...]
view.engine()->rootContext()->setContextProperty("thread", &t);

在您的 QML 中:

thread.start()

thread.quit()

如果你有这样的 SerialManager:

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

在main.cpp中添加以下代码:

qmlRegisterType<SerialManager>("Device",1,0,"Serial");

然后在您的 qml 中执行此操作:

 Component.onCompleted: {
            thread.start()
        }
 Component.onDestruction:
    {
        thread.quit()

    }

作为替代解决方案,更面向 QML,您可以导出 class 实用程序来完成从 C++ 到 QML 的工作,然后使用 WorkerScript(参见 here文档)生成一个新线程并执行一堆 JavaScript 代码来处理 class.

WorkerScript 意味着您可以:

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.

它会更干净,并且您可以避免在 QML 中处理烦人的 start 方法。