我想按按钮时启动QThread运行。但是编译器输出以下错误:

QThread: Destroyed while thread is still running
ASSERT failure in QThread::setTerminationEnabled(): "Current thread was not started with QThread.", file thread\qthread_win.cp.

我不知道我的代码有什么问题。

任何帮助,将不胜感激。

这是我的代码:
SamplingThread::SamplingThread( QObject *parent):
   QwtSamplingThread( parent ),
   d_frequency( 5.0 )
{
   init();
}

MainWindow::MainWindow( QWidget *parent ):
QMainWindow( parent )
{.......
  .....
   run= new QPushButton ("Run",this);
   stop= new QPushButton("Stop",this);
   connect(run, SIGNAL(clicked()),this, SLOT (start()));
}

MainWindow::start
{
   SamplingThread samplingThread;
   samplingThread.setFrequency( frequency() );
   samplingThread.start();
}

int main( int argc, char **argv )
{
   QApplication app( argc, argv );
   MainWindow window;
   window.resize( 700, 400 );
   window.show();
   bool ok = app.exec();
   return ok;
}

最佳答案

错误消息指出:QThread: Destroyed while thread is still running。您正在SamplingThread方法内创建MainWindow::start对象,但是当该方法终止时,它超出范围(即被销毁)。我看到两种简单的方法:

  • 您将SamplingThread设为MainWindow的成员,因此其生存期与MainWindow实例
  • 相同
  • 您使用一个指针,即使用以下命令创建SamplingThreadSamplingThread *samplingThread = new SamplingThread;

  • 这有帮助吗?

    编辑:说明这两种情况,一个很粗糙的例子来说明这两种情况
    #include <iostream>
    #include <QApplication>
    #include <QThread>
    
    class Dummy
    {
    public:
      Dummy();
      void start();
    private:
      QThread a;
    };
    
    Dummy::Dummy() :
      a()
    {
    }
    
    
    void Dummy::start()
    {
      a.start();
      QThread *b = new QThread;
      b->start();
    
      if( a.isRunning() ) {
        std::cout << "Thread a is running" << std::endl;
      }
      if( b->isRunning() ) {
        std::cout << "Thread b is running" << std::endl;
      }
    }
    
    int main(int argc, char** argv)
    {
      QApplication app(argc,argv);
      Dummy d;
      d.start();
      return app.exec();
    }
    

    10-08 04:57