Q_ENUM与Q_ENUMS的区别

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

可以参考帖子:https://woboq.com/blog/q_enum.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu-Eleven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值