Prevent Firing Signals in Qt

前端 未结 8 960
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 14:07

We have a QCheckBox object, when user checks it or removes check we want to call a function so we connect our function to stateChanged ( int state )

8条回答
  •  轮回少年
    2020-12-14 14:29

    Even in QT5, its a bit cumbersome when there are many/several things to block. Here's a multi-object version that is concise to use:

    class SignalBlocker
    {
    public:
      SignalBlocker(QObject *obj)
      {
        insert( QList()<  objects)
      {
        insert(objects);
      }    
      void insert(QList  objects)
      {
        for (auto obj : objects)
          m_objs.insert(obj, obj->signalsBlocked());
        blockAll();
      }    
      void blockAll() {
        for( auto m_obj : m_objs.keys() )
          m_obj->blockSignals(true);
      }    
      ~SignalBlocker()
      {
        for( auto m_obj : m_objs.keys() )
          m_obj->blockSignals( m_objs[m_obj] );
      }    
    private:
      QMap m_objs;      
    };
    

    usage:

    void SomeType::myFunction()
    {
        SignalBlocker tmp( QList() 
        << m_paramWidget->radioButton_View0
        << m_paramWidget->radioButton_View1
        << m_paramWidget->radioButton_View2
        );
        // Do more work, ... 
    }
    

提交回复
热议问题