What is the correct way to suppress Qt signals when values ​​are explicitly specified

I got from a QWidget derived class that contains three QSpinBoxes (e.g. coordinates). The valueChanged() signal is connected and emitted in at least these three cases:

  • up / down button
  • manually entered number
  • setValue()

However, when using setValue() I want to suppress the signal (s) since I do not want to have (three) signals. In my opinion, there are two ways to handle this:

  • QObject::blockSignals()
  • using a flag that indicates whether values ​​have been explicitly set

Both options work, but I think they are not straightforward: for the first, I completely block all signals. And I need to set blockSignals(true) for all unclassified widgets (blockSignals does not block child QObjects in my expression). For the second, I have to request a flag in each update method, and the signals are raised, although I do not need them.

Are there any general design patterns that prevent this behavior? If not, which option do you prefer?

+7
source share
1 answer

The third option will be to subclass QSpinBox, implement the necessary functionality there and use the derived class instead of QSpinBox - this hides all the associated complexity in the derived class and allows you to use it in the same way as QSpinBox.

For example, the following class

myQSpinBox.h

 #ifndef MYQSPINBOX_H #define MYQSPINBOX_H #include <QSpinBox> class myQSpinBox : public QSpinBox { Q_OBJECT public: myQSpinBox(QWidget * parent = 0 ); protected: bool valueBeingSet; public slots: void setValue (int val); private slots: void On_valueChanged(int val); signals: void valueChangedNotBySet(int val); }; #endif // MYQSPINBOX_H 

myQSpinBox.cpp

 #include "myQSpinBox.h" myQSpinBox::myQSpinBox(QWidget * parent) : QSpinBox(parent) , valueBeingSet(false) { connect(this,SIGNAL(valueChanged(int)),this,SLOT(On_valueChanged(int))); } void myQSpinBox::setValue ( int val ) { valueBeingSet = true; QSpinBox::setValue(val); valueBeingSet = false; } void myQSpinBox::On_valueChanged(int val) { if(!valueBeingSet) emit valueChangedNotBySet(val); } 

will highlight valueChangedNotBySet(int); in cases 1 and 2., but not in case 3., retaining all the functionality of QSpinBox

+4
source

All Articles