views:

329

answers:

3

The only way to enable threading demonstrated in qt documentation is through inheriting QThread and then override its run() method.

class MyThread : public QThread
 {
 public:
     void run();
 };

 void MyThread::run()
 {
     QTcpSocket socket;
     // connect QTcpSocket's signals somewhere meaningful
     ...
     socket.connectToHost(hostName, portNumber);
     exec();
 }

I wonder if there is any way to use qt thread without ever inheriting from any qt objects?

+2  A: 

QThread itself is derived from QObject. You need to override its run method to use it, therefore you have to inherit from QObject in order to use QThread.

Why do you want not to inherit from QObject?

erelender
+4  A: 

You can use multithreading without inheriting from QObject with QtConcurrent::run():

QFuture QtConcurrent::run ( Function function, ... )
Runs function in a separate thread. The thread is taken from the global QThreadPool. Note that the function may not run immediately; the function will only be run when a thread is available.

rpg
+1  A: 

If you do not wish to inherit QThread you could make a wrapper that inherits QThread and takes your objects as an argument, e.g. through a IRunnable interface (which you make and let your thread-classes inherit).

larsm