kaon的个人主页

http://www.qtcn.org/bbs/u/107506  [收藏] [复制]

kaon

  • 6

    关注

  • 20

    粉丝

  • 28

    访客

  • 等级:侠客
  • 总积分:267
  • 保密,2010-11-08

最后登录:2024-05-04

更多资料

日志

QFlags and enum 用法

2013-03-21 14:37
随手一翻,翻到一篇简易教程,用于安全使用QFlags


http://qt-project.org/wiki/QFlags_tutorial

Simple tutorial for safe-usage QFlags



Overview


First of all we should write about macro Q_FLAGSThis macro registers one or several flags types to the meta-object system[font=Verdana, 'DejaVu Sans', Geneva, sans-serif]

Example:




  1. class TestClass

  2. {

  3. public:

  4.      enum Option {

  5.          OptionA = 0x0,  // 0x000000

  6.          OptionB = 0x1,  // 0x000001

  7.          OptionC = 0x2,  // 0x000010

  8.          OptionD = 0x4,  // 0x000100

  9.          OptionE = 0x8,  // 0x001000

  10.          OptionF = 0x16 // 0x010000

  11.          // ... some more options with value which is a power of two

  12.      };

  13.      Q_DECLARE_FLAGS(Options, Option)

  14. };


  15. Q_DECLARE_OPERATORS_FOR_FLAGS(TestClass::Options)


The Q_DECLARE_FLAGS() macro expands to

  1. 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




  1. void test (TestClass::Options flag)

  2. {

  3.   if (flag.testFlag(TestClass::OptionA))

  4.     qDebug() << "A";

  5.   if (flag.testFlag(TestClass::OptionB))

  6.     qDebug() << "B";

  7. }


  8. int main()

  9. {

  10.   test (TestClass::OptionA | TestClass::OptionB);

  11.   test (0x1);  // error

  12. }


testFlag(flag) method checks if flag is set in QFlags.[font=Verdana, 'DejaVu Sans', Geneva, sans-serif]

Some example




  1. TestClass::Options f1(TestClass::OptionA | TestClass::OptionB);   // 000011

  2. TestClass::Options f2(~f1);                                       // 111100

  3. TestClass::Options f3(Foo::OptionA | Foo::OptionC);               // 000101

  4. TestClass::Options f4(f1^f3);                                     // 000110
分类:默认分类|回复:0|浏览:2859|全站可见|转载
 

Powered by phpwind v8.7 Certificate Copyright Time now is:05-05 00:37
©2005-2016 QTCN开发网 版权所有 Gzip disabled