View Full Version : Use QFlags
qt_developer
23rd May 2012, 16:51
Hi all,
How can I use QFlags (http://qt-project.org/doc/qt-4.8/qflags.html)?
I have always used C++ enum.
Can help me with an example?
Regards.
ChrisW67
24th May 2012, 01:31
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.
#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)
{
QCoreApplication app(argc, 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
f |= QFlag(0x40); // invalid value
qDebug() << f;
return 0;
}
qt_developer
25th May 2012, 08:34
Thanks!
I have written this 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;
¿How can I declare a QFlag inside the myClass class? Can you help me with an example?
Regards!
ChrisW67
25th May 2012, 11:35
Exactly as you have except the flag enum values should be powers of 2
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;
};
Compiles fine.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.