Hi all,
How can I use QFlags?
I have always used C++ enum.
Can help me with an example?
Regards.
Hi all,
How can I use QFlags?
I have always used C++ enum.
Can help me with an example?
Regards.
At its heart it still is a C++ enum, just with a wrapper. You use it much like you use a simple integer except that it enforces type safety.
Qt Code:
#include <QtCore> #include <QDebug> struct Test { enum MyFlag { A = 0x01, B = 0x02, C = 0x04, D = 0X80, // combinations AB = A | B }; Q_DECLARE_FLAGS(MyFlags, MyFlag) enum AnotherEnum { Q = 0x01 }; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Test::MyFlags) int main(int argc, char **argv) { Test::MyFlags f; qDebug() << f; f |= Test::D; qDebug() << f; f = Test::A | Test::B; qDebug() << f; qDebug() << f.testFlag(Test::B) << f.testFlag(Test::C); f = Test::AB; qDebug() << f; qDebug() << f.testFlag(Test::B) << f.testFlag(Test::C); f &= ~Test::B; // turn off B qDebug() << f; f = Test::B; Test::MyFlags g(Test::A | Test::C); f |= g; qDebug() << f; // These won't compile: type safety // f = 0x01; // f |= 0x08; // f = Test::Q; // It is not perfect protection but you have to force it qDebug() << f; return 0; }To copy to clipboard, switch view to plain text mode
Thanks!
I have written this code:
Qt Code:
namespace Test { enum TState { ENone = 0x0, EPause = 0x1, EPlay = 0x2 }; Q_DECLARE_FLAGS(TStates, TState) } Q_DECLARE_OPERATORS_FOR_FLAGS( Test::TStates ) class myClass { ... Test::TStates getState(){return state;} ... Test::TStates state;To copy to clipboard, switch view to plain text mode
¿How can I declare a QFlag inside the myClass class? Can you help me with an example?
Regards!
Exactly as you have except the flag enum values should be powers of 2
Compiles fine.Qt Code:
namespace Test { enum MyFlag { A = 0x01, // powers of two like this B = 0x02, C = 0x04, D = 0X08, E = 1 << 8, // or you can do it like this F = 1 << 9, G = 1 << 10, H = 1 << 11 }; Q_DECLARE_FLAGS(MyFlags, MyFlag) } Q_DECLARE_OPERATORS_FOR_FLAGS(Test::MyFlags) class MyClass { public: Test::MyFlags someFunc() { return flags; } private: Test::MyFlags flags; };To copy to clipboard, switch view to plain text mode
Bookmarks