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).
preguntado el 10 de marzo de 12 a las 10:03
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.
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..
El Documentación de QThread explicitly states that subclassing is the right thing to do:
Para crear sus propios hilos, subclase
This is somewhat puzzling though, because (as shobi points out in otra respuesta) it is an ugly design and there is an alternative solution.