I would like to start my QThread
when I push on button Run. But the compiler outputs following error:
QThread: Destroyed while thread is still running
ASSERT failure in QThread::setTerminationEnabled(): "Current thread was not started with QThread.", file thread\qthread_win.cp.
I don't know what is wrong with my code.
Any help would be appreciated.
Here is my code:
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;
}
As the error message states: QThread: Destroyed while thread is still running
. You are creating your SamplingThread
object inside the MainWindow::start
method but it goes out of scope (i.e. is destroyed) when that method terminates. There are two easy ways that I see:
SamplingThread
a member of your MainWindow
so its lifetime is the same as for the MainWindow
instanceYou use a pointer, i.e. you create the SamplingThread
using
SamplingThread *samplingThread = new SamplingThread;
Does this help?
Edit: to illustrate the two cases, a very crude example to show the two cases
#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();
}