
Originally Posted by
The Storm
I just wonder why it can't be done with my QThread subclass.
The conecpt of QThread is not easy to understand by a lot of people, especially because the official documentation of QThread is not sufficient or even correct.
During the lifetime of Qt4 QThread changed, but the documentation remained the same.
Why do signals and slots in a QThread subclass not work as expected?
The only code that runs in a thread other than the main thread is the code that is written in the run() function, or that is being called from the run() function.
However, you define signal and slot functions in the QThread subclass. If you create a QThread object in your program, this QThread object lives in the main thread. Therefor the signals and slots are also define in the main thread.
Like I said above, when you call a function of QThread or a subclass from within the run() function, it will also be performed in the new thread. No problem for signals.
Slots are much more complicated.
If for example you connect a slot in your QThread subclass in the constructor of your QThread subclass, this slot will be called in the main thread!
Some people use moveToThread from within their QThread subclass. Although this SEEMS to work, it is wrong. You want to have the QThread object live in your main thread.
Therefor it is suggested to create a QObject subclass, implement it like any other object. Then create a new QThread object and move the QObject object to the new QThread object. In the background, the whole QObject object is moved to a new thread, instantly executing the slots inside the new thread.
I guess you can compare it like this:
{
...
//slots
//signals
...
};
class MyThread: public QThread
{
...
//slots
//signals
...
};
To copy to clipboard, switch view to plain text mode
to
class MyObjectThread : public
{
public:
void run();
};
void MyObjectThread::run()
{
MyObject *obj = new MyObject;
connect(..., SIGNAL, obj, SLOT);
}
class MyObjectThread : public
{
public:
void run();
};
void MyObjectThread::run()
{
MyObject *obj = new MyObject;
connect(..., SIGNAL, obj, SLOT);
}
To copy to clipboard, switch view to plain text mode
Since the object is created in the run() function, it completely lives in the new thread.
Bookmarks