【问题标题】:How Start a Qthread from qml?如何从 qml 启动一个 Qthread?
【发布时间】:2016-02-24 15:02:20
【问题描述】:

我需要立即启动并停止 Qml 文件中的 QThread 扩展类。 有什么解决办法吗? 这是我的课:

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

【问题讨论】:

    标签: c++ qt qml qthread


    【解决方案1】:

    如果你有这样的 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()
    
        }
    

    【讨论】:

      【解决方案2】:

      是的,您可以使用 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()
      

      【讨论】:

        【解决方案3】:

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

        WorkerScript 是为了让您可以:

        使用 WorkerScript 在新线程中运行操作。这对于在后台运行操作很有用,这样主 GUI 线程就不会被阻塞。

        这样会更简洁,您可以避免在 QML 中处理烦人的 start 方法。

        【讨论】:

          猜你喜欢
          • 2023-03-09
          • 2021-03-14
          • 1970-01-01
          • 2016-03-14
          • 2012-05-16
          • 2014-09-05
          • 2022-08-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多