[Interest] QFlags: Typesafe way to check "any flag set"

Giuseppe D'Angelo giuseppe.dangelo at kdab.com
Sun Feb 22 22:17:57 CET 2026


Hi,

Il 19/02/26 08:31, Schimkowitsch Robert ha scritto:
> Hi Guiseppe,
> 
> thanks for the reply!
> 
> QT_TYPESAFE_FLAGS features prominently in the Qt documentation, see e.g https://doc.qt.io/qt-6/qflags.html#operator-and-eq

I think that's a mistake, as QT_TYPESAFE_FLAGS itself is never documented...

> What I found confusing is that operator!() is documented, but operator bool() is not. Also, the implicit conversion to int is not documented (at least I could not find it in the above page).

That's also a mistake. Would you mind filing a QTBUG for documentation?

> There is "toInt()", but then I'd have to explicitly write
> 
> if (flags.toInt())
>     // something
> 
> I noticed that I can apparently static_cast flags to bool, but if I want to return a bool from a function, I have to use the explicit cast (which would be fine, if that is the way it's supposed to work).

Going back to:

> #ifdef QT_TYPESAFE_FLAGS
>     constexpr inline explicit operator Int() const noexcept { return i; }
>     constexpr inline explicit operator bool() const noexcept { return i; }
> #else
>     constexpr inline Q_IMPLICIT operator Int() const noexcept { return i; }
>     constexpr inline bool operator!() const noexcept { return !i; }
> #endif

if QT_TYPESAFE_FLAGS is not defined (the default), then a QFlags object 
will implicitly convert to bool through the operator Int(), including on 
function return:

https://gcc.godbolt.org/z/oPjhM661G


If instead it is defined (not recommended), then you can still test them 
using `if (flags)`, but you need an explicit cast when using `return` or 
similar forms of copy initializations, because the operator towards bool 
becomes `explicit`. This is a somewhat annoying quirk of C++ that may 
cause source incompatibilities (cf. 
https://codereview.qt-project.org/c/qt/qtbase/+/311100 )

For example,

// under QT_TYPESAFE_FLAGS
QFlags<E> flags;

bool f() {
   bool ok = flags;   // ERROR
   bool ok { flags }; // OK
   if (flags) {}      // OK
   return flags;      // ERROR
   return bool(flags); // OK ; or (bool)flags, static_cast<bool>(flags), 
etc.
}



HTH,


-- 
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - Trusted Software Excellence
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4850 bytes
Desc: Firma crittografica S/MIME
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20260222/889290e5/attachment.bin>


More information about the Interest mailing list