Reputation: 7486
I read on internet that subclassing (that deriving a class from Qthread) and then over writing run function to perform the required task is not the correct way to use Qthread. But i have read in some books and on Qt documentation to use the subclassing way?
can you tell me why shouldn't use the subclassing way? Subclassing Qthread is an easy way to use thread (for me because i am a beginner).
Thanks.
Upvotes: 3
Views: 2043
Reputation: 4276
See this great article about QThread: The great QThread Mess by Christoph Eckert, which lead me to use QThread's this way, now: Threading without the headache by Bradley T. Hughes
Bottom line: IMHO, the easiest way to use QThread is to create an QObject subclass, use signals/slots and use moveToThread
to have the object live in a different thread with a different event loop.
Unfortunately, this doesn't work if you absolutely need a "while(true)"
kind of thread, but it is very often avoidable in Qt.
Upvotes: 2
Reputation: 182048
The QThread documentation explicitly states that subclassing is the right thing to do:
To create your own threads, subclass
QThread
and reimplementrun()
.
This is somewhat puzzling though, because (as shobi points out in another answer) it is an ugly design and there is an alternative solution.
Upvotes: 1
Reputation: 2129
QThread was designed and is intended to be used as an interface or a control point to an operating system thread, not as a place to put code that you want to run in a thread. We object-oriented programmers subclass because we want to extend or specialize the base class functionality. The only valid reasons I can think of for subclassing QThread is to add functionality that QThread doesn’t have, e.g. perhaps providing a pointer to memory to use as the thread’s stack, or possibly adding real-time interfaces/support. Code to download a file, or to query a database, or to do any other kind of processing should not be added to a subclass of QThread; it should be encapsulated in an object of it’s own.
for more details please check this..
http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
Upvotes: 1