How to use QThread in this case
HI:
I want to use one QThread to interactively handle user’s inputs events (mouse, keyboard, etc..)
The other thread to do things like drawing, moving data between memory and disk, or heavy computation.
Could anyone kind enough to give me some hints?
Thanks!
-Todd
11 replies
Hi Todd,
user input is send via events to widgets, and widgets MUST live in the main thread. You could derive from QApplication and send all user input as custom events to objects inside a thread (or put them to a queue which is handleded in the thread), but widgets always live in the main thread. This also applies to drawing to the widgets. The only thing you can do inside a thread, is drawing inside a pixmap and blit this pixmap then inside the main thread.
Memory operations, computations etc can surely be done inside a thread. I suggest you read pepes wiki article [developer.qt.nokia.com] on that.
And if I can use QImage for off-screen drawing as weel as QPixmap the what is the difference? The point is that currently I use QPixmap for off-screen drawing and I’m going to redesign my app to use non-gui thread for drawing. Does it mean that I will need to use QImage instead of QPixmap? Can I be sure that all methods of QPixmap I currently use can be found in QImage? If not – then what is the solution?
Hello,
Hmm… the documentation is confusing when it describes QPixmap as “off-screen”, because you need to convert a QImage into a QPixmap to display it on-screen. Anyway:
- QImage is a “data structure” class — it is an array of pixels in your program’s memory, so you can access a QImage from any thread in your program.
- QPixmap is tied to your OS’s windowing system — its memory is managed by the OS itself, so you can only access a QPixmap from the GUI thread.
I’d recommend:
- Manipulate pixels using a QImage, in a non-GUI thread
- Pass the finished QImage into your GUI thread
- In the GUI thread, convert the QImage into a QPixmap, and display it
Edit: I also recommend starting a new thread when you have a question
There’s a lot of things you can’t do when you draw in any thread other than the main thread. Font rendering will work differently, for example. The QImage you generate could be huge, depending on your scene.
I recommend thinking twice three times before outsourcing GUI to another thread.
If you have a performance or responsiveness issue,
- Optimize your code as it runs in the GUI thread
- Consider using a different GUI engine (e.g. GraphicsView, OpenGL,…)
- See what non-GUI-related data preparations you might be able to put into a separate thread. However, even this is going to make your program much more complicated.
You must log in to post a reply. Not a member yet? Register here!




