随手一翻,翻到一篇简易教程,用于安全使用QFlags http://qt-project.org/wiki/QFlags_tutorialSimple tutorial for safe-usage QFlagsOverviewFirst of all we should write about macro Q_FLAGS This macro registers one or several flags types to the meta-object system[font=Verdana, 'DejaVu Sans', Geneva, sans-serif]Example: class TestClass { public: enum Option { OptionA = 0x0, // 0x000000 OptionB = 0x1, // 0x000001 OptionC = 0x2, // 0x000010 OptionD = 0x4, // 0x000100 OptionE = 0x8, // 0x001000 OptionF = 0x16 // 0x010000 // ... some more options with value which is a power of two }; Q_DECLARE_FLAGS(Options, Option) }; Q_DECLARE_OPERATORS_FOR_FLAGS(TestClass::Options)
The Q_DECLARE_FLAGS() macro expands to typedef QFlags<Enum> Flags; [font=Verdana, 'DejaVu Sans', Geneva, sans-serif]In our case it expandes to typedef QFlags<Option> Options; [font=Verdana, 'DejaVu Sans', Geneva, sans-serif] where Option[font=Verdana, 'DejaVu Sans', Geneva, sans-serif] – is an enum name, and Options[font=Verdana, 'DejaVu Sans', Geneva, sans-serif] – is name for set of flags.The Q_DECLARE_OPERATORS_FOR_FLAGS() macro declares global operator|() functions for Flags, which is of type QFlags<T>. The Q_DECLARE_FLAGS() macro does not expose the flags to the meta-object system, so they cannot be used by Qt Script. To make the flags available for these purpose, the Q_FLAGS() macro must be used. [font=Verdana, 'DejaVu Sans', Geneva, sans-serif]Usage sample void test (TestClass::Options flag) { if (flag.testFlag(TestClass::OptionA)) qDebug() << "A"; if (flag.testFlag(TestClass::OptionB)) qDebug() << "B"; } int main() { test (TestClass::OptionA | TestClass::OptionB); test (0x1); // error }
testFlag(flag) method checks if flag is set in QFlags. [font=Verdana, 'DejaVu Sans', Geneva, sans-serif]Some example TestClass::Options f1(TestClass::OptionA | TestClass::OptionB); // 000011 TestClass::Options f2(~f1); // 111100 TestClass::Options f3(Foo::OptionA | Foo::OptionC); // 000101 TestClass::Options f4(f1^f3); // 000110
|