PDA

View Full Version : Invoking a slot from a static method in time



Momergil
22nd August 2014, 15:34
Hello!

Some time ago I open this thread (http://www.qtcentre.org/threads/59595-How-to-call-a-static-method-from-another-thread-without-having-to-use-signal-and-slot) to learn how could I call a static method from another thread. Back then I learned about the QMetaObject::invokeMethod which has since served me well.

Now the situation has slightly changed: I call my static method from whatever thread I want and, in that static method, I use QMetaObject::invokeMethod to a call a Singleton class's method:



void MessageFrame::critical(const message &text)
{
if (Q_UNLIKELY(!QMetaObject::invokeMethod(&instance(),"showMessage",Q_ARG(MessageFrame::Icon,MessageFrame::Critical), Q_ARG(MessageFrame::message,text))))
mDebugS("Failed invokeMethod in MessageFrame::critical");
}


Everything works fine, but I want to add a new feature: time control. I want to not simply call the static method, but tell it that, after some time, another method of the same Singleton class needs to be called:



void MessageFrame::critical(const message &text, const qint32 time)
{
if (Q_UNLIKELY(!QMetaObject::invokeMethod(&instance(),"showMessage",Q_ARG(MessageFrame::Icon,MessageFrame::Critical), Q_ARG(MessageFrame::message,text))))
mDebugS("Failed invokeMethod in MessageFrame::critical");

if (time > 0)
QTimer::singleShot(time,&instance(),SLOT(nextMessage()));
}


Something like that. The problem is: how can I do this? I have no idea apart from knowing that the above QTimer::singleShot() call don't work.


Momergil

anda_skoa
22nd August 2014, 15:51
If that doesn't work then the thread probably doesn't run an event loop and therefore can't process the timer event.

Since the cross-thread calling requires the owner thread of instance() to run one, you could add a method there that does that and call it via invokeMethod as usual.

Cheers,
_

Momergil
29th August 2014, 13:51
Thanks for the reply, anda_skoa, but doing some extra research I found out that actually the QTimer call was being made; it was the implementation of nextMessage() that was problematic and wasn't doing what I wanted :p

Everything working fine now.

Guess that should teach me not to come in such a hurry to a forum :x

Momergil