QFlags tutorial
Jump to navigation
Jump to search
[toc align_right="yes" depth="3"]
Simple tutorial for safe-usage QFlags
Overview
First of all we should write about macro <code>Q_FLAGS</code>
This macro registers one or several flags types to the meta-object system
Example:
class TestClass<br /> {<br /> public:<br /> enum Option {<br /> OptionA = 1, // 000001<br /> OptionB = 2, // 000010<br /> OptionC = 4, // 000100<br /> OptionD = 8, // 001000<br /> OptionE = 16, // 010000<br /> OptionF = 32 // 100000<br /> // … some more options with value which is a power of two<br /> };<br /> Q_DECLARE_FLAGS(Options, Option)<br /> };
Q_DECLARE_OPERATORS_FOR_FLAGS(TestClass::Options)
The <code>Q_DECLARE_FLAGS()</code> macro expands to
typedef QFlags&lt;Enum&gt; Flags;<code> In our case it expandes to <code&gt;typedef QFlags&lt;Option&gt; Options;</code&gt; where '''Option''' - is an enum name, and '''Options''' - is name for set of flags.
The <code&gt;Q_DECLARE_OPERATORS_FOR_FLAGS()</code&gt; macro declares global <code&gt;operator|()</code&gt; functions for Flags, which is of type <code&gt;QFlags&lt;T&gt;</code&gt;.
The <code&gt;Q_DECLARE_FLAGS()</code&gt; 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 <code&gt;Q_FLAGS()</code&gt; macro must be used.
== 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
}
<code&gt;testFlag(flag)</code&gt; method checks if flag is set in <code&gt;QFlags&lt;/code&gt;.
=== 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