QFlags tutorial: Difference between revisions
No edit summary |
AutoSpider (talk | contribs) (Add "cleanup" tag) |
||
Line 1: | Line 1: | ||
{{Cleanup | reason=Auto-imported from ExpressionEngine.}} | |||
[[Category:snippets]] | [[Category:snippets]] | ||
Revision as of 16:20, 3 March 2015
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine. Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean. |
[toc align_right="yes" depth="3"]
Simple tutorial for safe-usage QFlags
Overview
First of all we should write about macro
Q_FLAGS
This macro registers one or several flags types to the meta-object system
Example:
class TestClass
{
public:
enum Option {
OptionA = 1, // 000001
OptionB = 2, // 000010
OptionC = 4, // 000100
OptionD = 8, // 001000
OptionE = 16, // 010000
OptionF = 32 // 100000
// … 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;<code> In our case it expandes to <code>typedef QFlags<Option> Options;
where Option - is an enum name, and Options - 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.
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>testFlag(flag)
method checks if flag is set in
QFlags
.
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