0

Consider a QObject:

class TestObject: public QObject
{
        Q_OBJECT
    public slots:
        void doStuff();
};

We will run this object in some different thread:

TestObject* o = new TestObject;
o->moveToThread(someThreadPointer);

Now, how do I invoke doStuff so that it happens in the worker thread? If I have other object in main thread, I can do this:

class OtherObject: public QObject
{
        Q_OBJECT
    signals:
        signalToDoStuff();
};

In main thread then:

TestObject* o = new TestObject;
o->moveToThread(someThreadPointer);
OtherObject other* = new OtherObject;
QObject::connect(other, &OtherObject::signalToDoStuff, o, &TestObject::doStuff);
// Emit the signal which causes `doStuff` to be called in other thread
other->signalToDoStuff();

But that's a long way around. I need to queue up an event for doStuff to be called.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • The question it's a duplicate of is more general: it asks not merely how to invoke a slot, but more generally how to invoke any functor. – Kuba hasn't forgotten Monica Aug 03 '16 at 01:14
  • I think you want `QMetaObject::invokeMethod(testObject, "doStuff", Qt::QueuedConnection);`. – Jarod42 Aug 03 '16 at 01:37
  • @KubaOber With your attitude to closing questions any question can be closed based on the fact that the solution can be (maybe) derived from some other question on SO. This isn't how this works. I'm asking specifically about slots, so unless the other post is specifically about slots, or the solution regarding the slots is **exactly** the same, reopen this question. – Tomáš Zato Aug 03 '16 at 06:45
  • Any answer that will work with functors will work with slots, too. It really is a duplicate: all answers to the duplicate question are answers to your question. There's no deriving involved at all: you literally substitute the functor with a bound slot (via `std::bind` or a lambda) and that's it. You also phrased it slightly misleadingly: you don't care about `connect`, you care about not having to have extra signals. E.g. my answer to other question covers how you can avoid a custom class for signal emission by leveraging `QObject::destroyed` on a temporary object. – Kuba hasn't forgotten Monica Aug 03 '16 at 14:40
  • The only way this wouldn't be a duplicate if you wanted solutions that work in Qt 4, since obviously you can't `QMetaObject::invoke` a functor there. – Kuba hasn't forgotten Monica Aug 03 '16 at 14:42

0 Answers0