Q_GADGET 与 Q_OBJECT

1. 元对象系统The Meta-Object System

Qt的元对象系统提供了用于对象间通信的信号和槽机制(signals and slots)运行时类型信息( run-time type information)动态属性系统(dynamic property system)
元对象系统基于三个方面:

  • QObject类的派生类。
  • 在类声明前使用Q_OBJECT()宏来开启元对象功能,如动态属性、信号和槽。
  • 元对象编译器(MOC)为每个QObject派生类提供实现元对象功能所需的代码。

2. Q_OBJECT

Q_OBJECT宏可以赋予类元对象系统的三大功能:信号和槽机制(signals and slots)运行时类型信息( run-time type information)动态属性系统(dynamic property system)
Q_OBJECT宏要求类必须是QObject的子类,Q_OBJECT宏必须出现在类定义的私有部分中,该类定义声明自己的信号和槽,或者使用Qt的元对象系统提供的其他服务

3. Q_Gadget

Q_Gadget宏是Q_OBJECT宏的轻量级版本,适用于不继承QObject但仍希望使用QMetaObject提供的一些反射功能的类。
Q_Gadgets可以有Q_ENUMQ_PROPERTYQ_INVOKABLE,但它们不能使用信号和槽。

4. 属性系统

Qt有一个复杂的属性系统,它基于元对象系统,作为独立于编译器和平台的库。Qt解决方案适用于Qt支持的所有平台上的任何标准C++编译器。

5. 属性的声明

使用Q_PROPERTY()宏来声明属性,其格式为:

// []中是可选项
Q_PROPERTY(type name
             (READ getFunction [WRITE setFunction] |
              MEMBER memberName [(READ getFunction | WRITE setFunction)])
             [RESET resetFunction]
             [NOTIFY notifySignal]
             [REVISION int]
             [DESIGNABLE bool]
             [SCRIPTABLE bool]
             [STORED bool]
             [USER bool]
             [CONSTANT]
             [FINAL])

其中属性名和READ(MEMBER)是必选项,其他是可选项。type可以是任何QVariant支持的类型。
下面是一个案例:

class Customer : public QObject
{
    Q_OBJECT

    Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged)
    Q_PROPERTY(QString phone MEMBER m_phone NOTIFY phoneChanged)
    Q_PROPERTY(QDate dateEstablished READ getDateEstablished CONSTANT) // Read-only
    Q_PROPERTY(CustomerType type READ getCustomerType CONSTANT) // Read-only
    Q_PROPERTY(QString address READ getAddress WRITE setAddress)
public:
    enum CustomerType {
        Corporate, Individual, Educational, Government
    };
    Q_ENUM(CustomerType)
    Customer(CustomerType type, const QDate &dateEstablished, QObject* parent = nullptr);
    QString getName() const;
    void setName(const QString &name);

    QDate getDateEstablished() const;
    CustomerType getCustomerType() const;
    QString getAddress() const;
    void setAddress(const QString &address);
signals:
    void nameChanged();
    void phoneChanged();
    void addressChanged();
private:
    QString m_name;
    QString m_phone;
    QDate m_dateEstablished;
    CustomerType m_customerType;
    QString m_address;
};
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值