PDA

View Full Version : How to call a static method from another thread without having to use signal and slot



Momergil
26th June 2014, 12:48
Hello!

I have the following situation: I created a new class MessageFrame that should do the work of QMessageBox for an embedded solution, having the ::question, ::information, etc. static methods to be called from when I want. The main difference, though, from the QMessageBox class is that, instead of directly creating the static dialog, MessageFrame is implemented with the Singleton pattern (one static instance of the class is created and the static methods mentioned earlier all call to that unique instance).

Everything was fine till I needed to call those static methods from within a different thread then the main thread. When I did that, Qt began to send lots of errors and no MessageFrame at all and I remembered that there is such a problem of calling a show() method from an object from another thread.

The question is: how may I solve this problem? I know of at least one solution, but that I want to avoid: each time I want to call one of those static methods from this different thread, I emit a signal that is somewhere else connected to those static methods, now converted to slots. This would work as a signal and slot connection between different threads and, therefore, MessageFrame's show() would be called from inside the proper thread. But as I sad, I want to avoid this method.

So, is there another way of doing this?



Thanks,

Momergil

^NyAw^
26th June 2014, 12:53
Hi,

As Qt doc says, only the main thread can touch the GUI, so you have to use SIGNAL/SLOT mechanism.

What you would to achieve?

Momergil
26th June 2014, 12:56
What you would to achieve?

The idea is to use MessageFrame as close to QMessageBox as possible, that is, when I want to use it, I just call the static methods directly; no such kind of "previous configuration needed" wanted :/

anda_skoa
26th June 2014, 13:56
You can use QMetaObject::invokeMethod() to call slots like if they were called through a signal/slot connection.
You can obviously hide that behind a static method that has access to the receiver object pointer.

Cheers,
_

Momergil
26th June 2014, 18:27
You can use QMetaObject::invokeMethod()

Thanks, anda_skoa! It worked perfectly :)


Momergil