During Qt training, I ran into this problem with a set of interconnected widgets that I wanted to update atomically. I liked @cjhuitt's solution, but it turned out that it goes even better with a little syntax sugar based on proxy objects . Here's the approach I used ...
First, I defined a class template for a proxy blocker object. Like Caleb, this blocks building signals, and then restores their former state upon destruction. However, it also overloads the -> operator to return a pointer to a locked object:
template<class T> class Blocker { T *blocked; bool previous; public: Blocker(T *blocked) : blocked(blocked), previous(blocked->blockSignals(true)) {} ~Blocker() { blocked->blockSignals(previous); } T *operator->() { return blocked; } };
Then I defined a small template function to build and return a blocker:
template<class T> inline Blocker<T> whileBlocking(T *blocked) { return Blocker<T>(blocked); }
Combining all this, I would use it as follows:
whileBlocking(checkBox)->setChecked(true);
or
whileBlocking(xyzzySpin)->setValue(50);
This gives me all the benefits of RAII, with auto-paired locking and recovery around the method call, but I don't need to specify any shell or state flags. It is beautiful, easy and beautifully agile.
Boojum Jun 22 '14 at 8:10 2014-06-22 08:10
source share