Callback function to Qt UI from non ui classes
I am using a third party library from which i want to give a callback to UI( written in qt) upon some events. I am registring the call back with the function pointer of the UI but when i get the call back i get following error "QObject::startTimer: QTimer can only be used with threads started with QThread" and "QPixmap: It is not safe to use pixmaps outside the GUI thread" and segmentation fault.
I searched and found i cant call the UI functions directly as it is called in a different thread
I wanted to know how can i register the call back fu开发者_如何学Gonction to update the UI.
The solution is threefold:
- Use QThread to instantiate your worker thread.
- Use QImage instead of QPixmap. QPixmaps are stored in the graphics subsystem and therefore controlled by the main (GUI) thread. QImages live in memory and can be held by any thread.
- Use the signal/slot concept. It is legal to emit a signal from other threads than the main thread.
Only if you want to also receive signals inside your worker thread, e.g. feedback from user input (like "cancel" button), you need a QT event loop in your worker thread, too. Your QTimer won#t work if it is to trigger a slot in the worker thread w/o event loop.
Read http://doc.trolltech.com/4.5/threads.html
Well, it sounds like you need two things:
- Set up a non-GUI QObject class with signals and slots for the callbacks.
- Ensure this class and/or its functions are called/created from the main program GUI thread, possibly as a (pointer) data member that exists as long as the program runs.
I think this would solve the interop problems.
精彩评论