The*_*Man 8 c++ qt signals-slots qthread qwt
QThread当我按下按钮Run时,我想启动我.但编译器输出以下错误:
QThread: Destroyed while thread is still running
ASSERT failure in QThread::setTerminationEnabled(): "Current thread was not started with QThread.", file thread\qthread_win.cp.
Run Code Online (Sandbox Code Playgroud)
我不知道我的代码有什么问题.
任何帮助,将不胜感激.
这是我的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*rik 22
正如错误消息所述:QThread: Destroyed while thread is still running.您正在方法SamplingThread内创建对象,MainWindow::start但是当该方法终止时,它会超出范围(即被销毁).我看到了两种简单的方法:
SamplingThread的成员,MainWindow因此其生命周期与MainWindow实例相同您使用指针,即您创建SamplingThread使用
SamplingThread *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();
}
Run Code Online (Sandbox Code Playgroud)
这是C ++的基础!您正在QThread堆栈上而不是堆上创建本地对象,因此当您离开method时,它会立即销毁MainWindow::start。
应该这样做:
MainWindow::MainWindow( QWidget *parent ):
QMainWindow( parent )
{
...
samplingThread = SamplingThread(this);
samplingThread->setFrequency( frequency() );
run= new QPushButton ("Run",this);
stop= new QPushButton("Stop",this);
connect(run, SIGNAL(clicked()), samplingThread, SLOT(start()));
}
MainWindow::~MainWindow() {
samplingThread->waitFor(5000);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29690 次 |
| 最近记录: |