Can Qt signals return a value?

后端 未结 5 1659
执念已碎
执念已碎 2020-12-03 04:35

Boost.Signals allows various strategies of using the return values of slots to form the return value of the signal. E.g. adding them, forming a vector out of th

5条回答
  •  無奈伤痛
    2020-12-03 04:56

    OK. So, I did a little more investigating. Seems this is possible. I was able to emit a signal, and receive value from the slot the signal was connected to. But, the problem was that it only returned the last return value from the multiple connected slots:

    Here's a simple class definition (main.cpp):

    #include 
    #include 
    
    class TestClass : public QObject
    {
        Q_OBJECT
    public:
        TestClass();
    
    Q_SIGNALS:
        QString testSignal();
    
    public Q_SLOTS:
        QString testSlot1() {
            return QLatin1String("testSlot1");
        }
        QString testSlot2() {
            return QLatin1String("testSlot2");
        }
    };
    
    TestClass::TestClass() {
        connect(this, SIGNAL(testSignal()), this, SLOT(testSlot1()));
        connect(this, SIGNAL(testSignal()), this, SLOT(testSlot2()));
    
        QString a = emit testSignal();
        qDebug() << a;
    }
    
    int main() {
        TestClass a;
    }
    
    #include "main.moc"
    

    When main runs, it constructs one of the test classes. The constructor wires up two slots to the testSignal signal, and then emits the signal. It captures the return value from the slot(s) invoked.

    Unfortunately, you only get the last return value. If you evaluate the code above, you'll get: "testSlot2", the last return value from the connected slots of the signal.

    Here's why. Qt Signals are a syntax sugared interface to the signaling pattern. Slots are the recipients of a signal. In a direct connected signal-slot relationship, you could think of it similar to (pseudo-code):

    foreach slot in connectedSlotsForSignal(signal):
        value = invoke slot with parameters from signal
    return value
    

    Obviously the moc does a little more to help in this process (rudimentary type checking, etc), but this helps paint the picture.

提交回复
热议问题