You don't need to subclass QThread in this particular case. And in general, abstain from subclassing QThread unless you are sure it is what you need.
Here is a quick example how to setup a worker and timer in a thread and launch it:
the worker class:
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0) : QObject(parent) {}
signals:
void doSomething();
public slots:
void trigger() {
emit doSomething();
}
};
main.cpp
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MainThreadObject o;
QThread *thread = new QThread;
Worker w;
QTimer timer;
timer.setInterval(1000);
timer.moveToThread(thread);
w.moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), &timer, SLOT(start()));
QObject::connect(&w, SIGNAL(doSomething()), &o, SLOT(doSomething()));
QObject::connect(&timer, SIGNAL(timeout()), &w, SLOT(trigger()));
thread->start();
return a.exec();
}
So, we have the MainThreadObject
which represents a QObject derived living in the main thread. We create the timer and Worker
object, which is just used to wrap a signal and slot to avoid the need of subclassing QThread. The timer is setup and it and the worker are moved to the new thread, the thread started()
signal is connected to the timer start()
slot, the worker doSomething()
signal is connected to the main thread object doSomething()
slot, and finally the timer timeout()
signal is connected to the worker trigger()
slot. Then the thread is started which initiates the entire chain in the event loop.
As a result, the MainThreadObject::doSomething()
is called every second, with the signal emitted from the secondary thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…