How to disconnect a signal with a slot temporarily in Qt?

后端 未结 2 440
名媛妹妹
名媛妹妹 2021-02-01 20:26

I connect a slot with a signal. But now I want to disconnect them temporarily.

Here is part of my class declaration:

class frmMain : public QWidget
{
           


        
2条回答
  •  囚心锁ツ
    2021-02-01 20:43

    There is a very nice function in QObject that comes in handy every now and again: QObject::blockSignals()

    Here's a very simple fire-and-forget class that will do what you want. I take no credit for it's design, I found it on the internet somewhere a long time ago. Be careful though, it will block all signals to all objects. If this is not what you want, you can modify the class to suit your needs.

    class SignalBlocker{
    public:
        SignalBlocker(QObject *o): object(o), alreadyBlocked(object->signalsBlocked()){
            if (!alreadyBlocked){
                object->blockSignals(true);
            }
        }
        ~SignalBlocker() {
            if (!alreadyBlocked){
                object->blockSignals(false);
            }
        }
    
    private:
        QObject *object;
        bool alreadyBlocked;
    };
    

    Usage, in your case, becomes trivial

    void frmMain::on_btnDownload_clicked()
    {
        SignalBlocker timerSignalBlocker(myReadTimer);
    
        ...//the code that I want myReadTimer to leave me alone
    
        // signals automatically unblocked when the function exits
    }
    

    UPDATE:

    I see that from Qt 5.3, a very similar class has been offically added to the API. It does a similar job as the one above with a slightly bigger feature-set. I suggest you use the official QSignalBlocker class instead in order to keep your codebase up-to-date with any API changes.

    Usage, however, remains exactly the same.

提交回复
热议问题