PDA

View Full Version : QWidget and thread safety



spraff
21st January 2009, 15:13
I need to call certain methods on a QWidget from a thread other than the main GUI thread. I understand this isn't safe, but it is safe to post events to a QWidget that can be processed asynchronously.

At the moment the only methods I need to call in this fashion are width() height() update() and resize(...), but this may grow.

Is there a page of documentation somewhere which maps method calls to equivalent QEvents which could be posted to the same effect?

I expect width() and height() are safe, if by accident rather than design, and there's a promising QResizeEvent, but what about update()?

Is this a sensible solution? Or should I perhaps subclass QEvent to store the desired calls? Or something else?

Thanks for your advice

spraff
21st January 2009, 15:27
Perhaps I should add, my experiments with Events has been a bit iffy so far,
this:



QObject * target = parent() ? parent() : this;
QEvent * event = new QResizeEvent(QSize(w,h),size());
QApplication::postEvent (target, event);


has no effect (parent is a QMainWindow), and this:



QApplication::postEvent (this, new QPaintEvent (QRect(0,0,width(),height())));


Causes a "QPainter::begin: Widget painting can only begin as a result of a paintEvent" message to be printed.

caduel
21st January 2009, 16:20
docs:

Resize events are sent to widgets that have been resized.
So I would not assume that sending a QResizeEvent will resize a widget.

Moreover, being "lucky" on height() etc is not something I would want to depend upon.
I suggest you just (if nec. create and) call the appropriate slots on the widget.
If it is just one widget (maybe your own class): easy. just add the slots.

If it is a widget with "closed" source (for you), you can create a helper class that has those slots and then forwards the calls to the widget you want to modify.

HTH

wysota
22nd January 2009, 01:11
You can create your own artificial events that you will send back and forth between threads to ask and respond to queries but this might be a significant amount of work if the number of methods you want to call grows. Honestly I don't see a reason why would anyone want to know the geometry of some widget from within another thread...