QGraphicsItem item;
item.setFlags(0x01); //语法不过,提示无法从int转flags
主要是因为QFlags的赋值运算符不允许直接输入整型数,Qt文档的说明
The QFlags class is a template class, where Enum is an enum type. QFlags is used throughout Qt for storing combinations of enum values.
The traditional C++ approach for storing OR-combinations of enum values is to use an int or uint variable. The inconvenience with this approach is that there’s no type checking at all; any enum value can be OR’d with any other enum value and passed on to a function that takes an int or uint.
Qt uses QFlags to provide type safety.
If you try to pass a value from another enum or just a plain integer other than 0, the compiler will report an error. If you need to cast integer values to flags in a untyped fashion, you can use the explicit QFlags constructor as cast operator.
解决办法是构造QFlags
item.setFlags(QGraphicsItem::GraphicsItemFlags(0x01));
然后,QFlags提供了与、或、非、异或运算符,所以遇到整型数或者非模板(QFlags< Enum>)枚举变量都要先转换为QFlags对象再作运算和赋值。但奇怪的是,只有与运算是支持整型数操作数的,而其余运算只允许操作数是QFlags对象或者模板枚举类型Enum,所以遇到这个差异时不用觉得奇怪:
QFlags operator&(int mask) const //支持整型操作数
QFlags operator&(uint mask) const //支持整型操作数
QFlags operator&(Enum mask) const
QFlags & operator&=(int mask) //支持整型操作数
QFlags & operator&=(uint mask) //支持整型操作数
QFlags & operator&=(Enum mask)
QFlags & operator=(const QFlags &other)
QFlags operator^(QFlags other) const
QFlags operator^(Enum other) const
QFlags & operator^=(QFlags other)
QFlags & operator^=(Enum other)
QFlags operator|(QFlags other) const
QFlags operator|(Enum other) const
QFlags & operator|=(QFlags other)
QFlags & operator|=(Enum other)
QFlags operator~() const