I've read lots of articles about why subclassing QThread
is a bad idea in most cases and how to use QThread
properly, invoking moveToThread
method. Here we can see a typical example of such design.
The class I am designing should meet the following requirements:
It want to use signals and slots, so I will need an event loop and will use
moveToThread
.It will expose the interface with signals and slots only. No ordinary C++ methods.
All slots should be executed in object's dedicated thread, one thread per object. So the thread should be created as the object is created and should finish when the object dies.
Thus an obvious solution comes to mind (not tested, just a sketch code):
class Worker : public QObject {
Q_OBJECT
public:
Worker() {
thread = new QThread();
// ...Some signal-slot connections may be done here...
// ...Some other connections may be performed by user code...
moveToThread(thread);
thread->start();
}
~Worker() {
thread->exit();
thread->wait();
delete thread;
}
public slots:
void process(); // and other interface slots
signals:
// Interface signals
private:
QThread* thread;
};
So the point is to declare QThread
object as a (private) member of worker class, but I've never ever seen that in any examples or other people's code.
That's why I wonder if this design is flawed? Does it have some fatal drawbacks I didn't notice? Or it's okay, but just not often needed?