使用场景:
项目中使用到了枚举:
enum ContextMenuTypeFlags
{
CONTEXTMENU_TYPEFLAG_NONE = 0,
CONTEXTMENU_TYPEFLAG_PAGE = 1 << 0,
CONTEXTMENU_TYPEFLAG_FRAME = 1 << 1,
CONTEXTMENU_TYPEFLAG_LINK = 1 << 2,
CONTEXTMENU_TYPEFLAG_MEDIA = 1 << 3,
CONTEXTMENU_TYPEFLAG_SELECTION = 1 << 4,
CONTEXTMENU_TYPEFLAG_EDITABLE = 1 << 5,
} ;
可能使用的情况有 value=CONTEXTMENU_TYPEFLAG_EDITABLE|CONTEXTMENU_TYPEFLAG_SELECTION等多种情况,于是想到了Qt中使用Qt::WindowFlags时可以直接赋值,于是点开Qt::WindowFlags查看源码,发现了Q_DECLARE_FLAGS
enum WindowState {
WindowNoState = 0x00000000,
WindowMinimized = 0x00000001,
WindowMaximized = 0x00000002,
WindowFullScreen = 0x00000004,
WindowActive = 0x00000008
};
Q_DECLARE_FLAGS(WindowStates, WindowState)
继续深入才知道原来都是QFlags的功劳.
#define Q_DECLARE_FLAGS(Flags, Enum)\
typedef QFlags<Enum> Flags;
使用方法,在类里面声明
class A{
...
public:
Q_DECLARE_FLAGS(CMTypeFlags, ContextMenuTypeFlags);//CMTypeFlags名称,ContextMenuTypeFlags为枚举类型
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::CMTypeFlags)
使用时这样调用即可
CMTypeFlags flags = CONTEXTMENU_TYPEFLAG_EDITABLE|CONTEXTMENU_TYPEFLAG_SELECTION;
//如果flags中有CONTEXTMENU_TYPEFLAG_EDITABLE标志,则返回true
if(flags.testFlag(CONTEXTMENU_TYPEFLAG_EDITABLE)){
}
更多详细的使用方法,可以文档中看QFlags