QThread not running in different thread
I am trying to create a thread with an object inside it that does some work periodically (using a QTimer). My idea was to subclass QThread and have all communication as well as the timed event run through the event-loop. But with my current example, everything seems to still run in the same thread.
This is the thread-class.
Code:
{
Q_OBJECT
private:
public:
void run(void);
public slots:
void startTimer(int timeout);
void _timeout(void);
};
void
thread::run(void) {
/* start the event-loop */
exec();
}
void
thread::startTimer(int timeout) {
if(!_timer)
QObject::connect(_timer,
SIGNAL(timeout
()),
this,
SLOT(_timeout
()));
_timer->setInterval(timeout);
_timer->start();
}
void
threadn::_timeout(void) {
qDebug
() <<
"timeout from" <<
QThread::currentThreadId();
}
This is what I run from my 'main' thread:
Code:
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
thread *t = new thread();
QObject::connect(this,
SIGNAL(startTimer
(int)), t,
SLOT(startTimer
(mode,
int)), Qt
::QueuedConnection);
t
->start
(QThread::HighestPriority);
qDebug
() <<
"Hello from " <<
QThread::currentThreadId();
emit startTimer(1000);
}
Re: QThread not running in different thread
Re: QThread not running in different thread
Thanks for the link!
After reading some more I found that threading in Qt does not work as I thought. The following does seem to work:
Code:
/* notice that thread no longer inherits from QThread */
{
Q_OBJECT
private:
public slots:
void startTimer(int timeout);
void _timeout(void);
};
void
thread::startTimer(int timeout) {
if(!_timer)
QObject::connect(_timer,
SIGNAL(timeout
()),
this,
SLOT(_timeout
()));
_timer->setInterval(timeout);
_timer->start();
}
void
threadn::_timeout(void) {
qDebug
() <<
"timeout from" <<
QThread::currentThreadId();
}
Now create a QThread object and move the instance of 'thread' to it.
Code:
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
thread *t = new thread();
QObject::connect(this,
SIGNAL(startTimer
(int)), t,
SLOT(startTimer
(mode,
int)), Qt
::QueuedConnection);
t->moveToThread(qthread);
qthread
->start
(QThread::HighestPriority);
qDebug
() <<
"Hello from " <<
QThread::currentThreadId();
emit startTimer(1000);
}