In C# you can do the following whenever you need to upda开发者_如何转开发te the gui from another thread:
control.Invoke(delegate()
{
// Do whatever you want in the gui thread here
});
Is there something similar and as simple for Qt4? (PyQt4 specifically)
I would rather not get into signals, slots, and use native threads instead of QThreads if possible.What's the simplest way to update a Qt4 gui from a non-qt (native) thread?
I'm not sure if this is easier than signals and slots but in some instances I like to use custom events.
In some QObject
subclass like MyObject
, you override customEvent()
to do some activity based on one of your custom events.
You can post a custom event to MyObject
from any thread using QCoreApplication::postEvent()
. This will require the caller to know a bit of Qt. To get around this, I like to write a method on MyOjbect
that encapsulates creating the custom event and posting it to itself.
The posting is asynchronous and the execution in customEvent()
runs in the gui thread.
If you need to pass in data, subclass QEvent
with setters and getters.
This is a pretty brief overview but the docs should help. If you have problems, I can post some code.
Signals can cross threads - thats the main point of them.
In general in Qt the gui thread is the only one allowed to update the gui, the normal simplest solution would have the gui running a timer and redrawing itself reading any progress from a function or variable in the worker thread.
The easiest way is to use signals and slots, as the qt documentation states
Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, QCoreApplication::exec() must also be called from that thread.
Signals can be delivered immediately or deferred (via a queue) by using a queue you can signal from one thread to the other.
To go without signals you would have to implement your own thread to thread communication, probably another queue.
精彩评论