what is the correct way to implement a QThread… (example please…)

About the only thing I can think of to add is to further state that QObjects have an affinity with a single thread. This is usually the thread that creates the QObject. So if you create a QObject in the app’s main thread and want to use it in another thread, you need to use moveToThread() to change the affinity.

This saves having to subclass QThread and creating your objects in the run() method, thus keeping your stuff nicely encapsulated.

That blog post does include a link to an example. It is pretty short but it shows the basic idea. Create your QObjects, connect your signals, create your QThread, move your QObjects to the QThread and start the thread. The signal/slot mechanisms will ensure that thread boundaries are crossed properly and safely.

You may have to introduce synchronization if you have to call methods on your object outside of that mechanism.

I know Qt has some other nice threading facilities beyond threads that are probably worth getting familiar with but I have yet to do so 🙂

Leave a Comment