Guard Class | Extending Qt Creator Manual
Description: The Guard class implements a recursive guard with locking mechanism.

- Extending Qt Creator Manual
- QtCreator
- Guard
- Extending Qt Creator Manual 13.0.1

# Guard Class

class Utils::Guard

The Guard class implements a recursive guard with locking mechanism. More...

Header: | #include <Guard>

## Detailed Description

It may be used as an alternative to QSignalBlocker. QSignalBlocker blocks all signals of the object which is usually not desirable. It may also block signals which are needed internally by the object itself. The Guard and GuardLocker classes don't block signals at all.

When calling a object's method which may in turn emit a signal which you are connected to, and you want to ignore this notification, you should keep the Guard object as your class member and declare the GuardLocker object just before calling the mentioned method, like:

     class MyClass : public QObject
     {
     \dots
     private:
         Guard updateGuard; // member of your class
     };

     \dots

     void MyClass::updateOtherObject()
     {
         GuardLocker updatelocker(updateGuard);
         otherObject->update(); // this may trigger a signal
     }

Inside a slot which is connected to the other's object signal you may check if the guard is locked and ignore the further operations in this case:

     void MyClass::otherObjectUpdated()
     {
         if (updateGuard.isLocked())
             return;

         // we didn't trigger the update
         // so do update now
         \dots
     }

The GuardLocker unlocks the Guard in its destructor.

The Guard object is recursive, you may declare many GuardLocker objects for the same Guard instance and the Guard will be locked as long as at least one GuardLocker object created for the Guard is in scope.