代码之家  ›  专栏  ›  技术社区  ›  yan bellavance

在QThread中是否需要调用QThread.exec()方法?

  •  7
  • yan bellavance  · 技术社区  · 16 年前

    我不打电话 exec() 在我的代码中,但是 timer 和 QUdpSocket 行政长官() event 要继续吗?

    我在工作,因为我没有打电话 moveToThread(this) 上 QThread QThread 实际上,它仍然是 main thread 量子插座 嗯,我使用投票 functions . 因此,它不需要与 signals .

    小贴士:如果你需要的话 init 东西,那需要一个 event loop ,你可以 delay 使命感 moveToThread 直到你不需要 信号 run() this QThread 指向变量的指针,并使 call

    3 回复  |  直到 10 年前
        1
  •  2
  •   drahnr    7 年前

    moveToThread(this) 在线程构造函数中,并在受保护的 run() QThread派生类的方法。

    分离线程执行循环可防止QApplication循环被非ui相关信号和插槽弄乱,从而延迟。例如,button click的插槽执行,使应用程序“滞后”。

    注意:通常你 子类QThread,请参见 Qt doc 更多信息

    编辑:Qt文档错误,请阅读此线程 https://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/

        2
  •  4
  •   Kaleb Pederson    16 年前

    您的计时器和套接字可能正在使用调用时启动的主事件循环 QCoreApplication::exec() . 虽然我确信在线程中运行事件循环有很好的理由,但我想不出一个理由。

    这个 QThread documentation

    每个QThread都可以有自己的事件循环。可以通过调用exec()启动事件循环;您可以通过调用exit()或quit()来停止它。在一个线程中有一个事件循环,可以使用一种称为排队连接的机制,将来自其他线程的信号连接到此线程中的插槽。它还可以在线程中使用需要事件循环的类,例如QTimer和qtcsocket。但是,请注意,在线程中不可能使用任何小部件类。

    QTimer ,需要一个必须调用的正在运行的事件循环 QThread::exec() . 其他课程,比如 QTCPSocket

        3
  •  1
  •   Rozi    16 年前

    void MyThread::run(){
      Curl * curl = new Curl();
      connect( curl, SIGNAL(OnTransfer(QString)), this, SLOTS(OnTransfer(QString)) );
      connect( curl, SIGNAL(OnDone()), curl, SLOTS(deleteLater()) );
      curl->Download("http://google.com");
      exec(); // this is an event loop in this thread, it will wait until you command quit()
    }
    
    void MyThread::OnTransfer(QString data){
      qDebug() << data;
    }
    

    这 (假设MyThread父线程是主线程)作为父线程:

    MyThread::MyThread(){
      curl = new Curl(this);
      connect( curl, SIGNAL(OnTransfer(QString)), this, SLOTS(OnTransfer(QString)) );
      start();
    }
    void MyThread::run(){
      curl->Download("http://google.com");
    }