Q_ENUMS:
This function is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.
This macro registers one or several enum types to the meta-object system.
先看例子:
widget.h
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
#if 0
//可以这样写
Q_ENUMS(Action)
public:
enum Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };//这段话不能写到public上面
#endif
// ERROR:1 不能写在public之上
// enum Priority { High, Low, VeryHigh, VeryLow };
// Q_ENUM(Priority)
// //ERROR2 不能一个在 public之上,一个在public之下
// enum Priority { High, Low, VeryHigh, VeryLow };
public:
//也可以这样写
enum Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };//这段话不能写到public上面
Q_ENUMS(Action)
//end Q_ENUMS
// ERROR3:不能Q_ENUM在枚举之上
// Q_ENUM(Priority)
// enum Priority { High, Low, VeryHigh, VeryLow };
enum Priority { High, Low, VeryHigh, VeryLow };
Q_ENUM(Priority)
Widget(QWidget *parent = nullptr);
~Widget();
void printEnums(Action a);
void printEnum(Priority p);
};
widget.cpp
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
printEnums(Action::Undo);
printEnums(Widget::Save);
printEnum(Priority::VeryLow);
}
Widget::~Widget()
{
}
void Widget::printEnums(Action a)
{
qDebug()<<"Q_ENUMS a="<<a;
}
void Widget::printEnum(Priority p)
{
qDebug()<<"Q_ENUM p="<<p;
}
输出结果:
总结:
Q_ENUM
is like the old Q_ENUMS
but with those differences:
- It needs to be placed after the enum in the source code.
- Only one enum can be put in the macro.
- It enables
QMetaEnum::fromType<T>()
. - These enums are automatically declared as a QMetaTypes (no need to add them in
Q_DECLARE_METATYPE
anymore). - enums passed to qDebug will print the name of the value rather than the number.
- When put in a QVariant,
toString
gives the value name. - The value name is printed by QCOMPARE (from Qt 5.6).