Can Qt signals return a value?

后端 未结 5 1673
执念已碎
执念已碎 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:46

    You may get a return value from Qt signal with the following code:

    My example shows how to use a Qt signal to read the text of a QLineEdit. I'm just extending what @jordan has proposed:

    It should be possible to modify your code in such a way to use "out" parameters that act as your "return".

    #include 
    #include 
    
    class SignalsRet : public QObject
    {
        Q_OBJECT
    
    public:
        SignalsRet()
        {
            connect(this, SIGNAL(Get(QString*)), SLOT(GetCurrentThread(QString*)), Qt::DirectConnection);
            connect(this, SIGNAL(GetFromAnotherThread(QString*)), SLOT(ReadObject(QString*)), Qt::BlockingQueuedConnection);
            edit.setText("This is a test");
        }
    
    public slots:
        QString call()
        {
            QString text;
            emit Get(&text);
            return text;
        }
    
    signals:
        void Get(QString *value);
        void GetFromAnotherThread(QString *value);
    
    private slots:
        void GetCurrentThread(QString *value)
        {
            QThread *thread = QThread::currentThread();
            QThread *mainthread = this->thread();
            if(thread == mainthread) //Signal called from the same thread that SignalsRet class was living
                ReadObject(value);
            else //Signal called from another thread
                emit GetFromAnotherThread(value);
        }
    
        void ReadObject(QString *value)
        {
            QString text = edit.text();
            *value = text;
        }
    
    private:
        QLineEdit edit;
    
    };
    

    To use this, just request call();.

提交回复
热议问题