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.
{
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();
}
class thread : public QThread
{
Q_OBJECT
private:
QTimer *_timer;
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)
_timer = new QTimer();
QObject::connect(_timer, SIGNAL(timeout()), this, SLOT(_timeout()));
_timer->setInterval(timeout);
_timer->start();
}
void
threadn::_timeout(void) {
qDebug() << "timeout from" << QThread::currentThreadId();
}
To copy to clipboard, switch view to plain text mode
This is what I run from my 'main' thread:
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);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(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);
}
To copy to clipboard, switch view to plain text mode
Bookmarks