Qt提供了基于元对象系统的属性系统,要在一个类中声明属性,该类必须继承QObject类,而且还要在声明前加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])
其中,type表示属性的类型,可以是QVariant支持的类型或者是用户自定义的类型。name就是属性的名称。READ后面是读取该属性的函数,MEMBER用于将属性与指定的成员变量相关联,READ和MEMBER二者选一。其它带[]的选项是可选的。一个属性类似于一个数据成员,不过它添加了一些可以通过元对象系统访问的附加功能。
举例:
Q_PROPERTY(QString userName READ getUserName WRITE setUserName)
----------------------------------------------------------------------------------------------------------------
读写属性值
1.使用与属性相关联的函数READ和WRITE进行读写
2.使用 QObject::property 和QObject::setProperty函数进行读写
3.若属性使用MEMBER与某个数据成员相关联,则可通过读写数据成员的值来间接读写属性的值
ps:当使用QObject::setProperty函数写属性值时,若属性未使用 Q_PROPERTY进行声明,则把该属性和值作为新属性添加到对象中,这就是动态属性。
----------------------------------------------------------------------------------------------------------------
具体例子:
//myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QString userName READ getUserName WRITE setUserName
NOTIFY userNameChanged) // 注册属性userName
public:
MyClass(QObject *parent = 0){}
QString getUserName() const // 实现READ读函数
{
return m_userName;
}
void setUserName(QString userName) // 实现WRITE写函数
{
m_userName = userName;
emit userNameChanged(userName);//NOTIFY信号触发需要在WRITE关联的函数中加入触发代码
}
signals:
void userNameChanged(QString); // 声明NOTIFY通知消息
private:
QString m_userName; // 私有变量,存放userName属性的值
};
#endif // MYCLASS_H
//mywidget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget() {}
private slots:
void userChanged(QString);
};
#endif // WIDGET_H
//mywidget.cpp
#include "widget.h"
#include "myclass.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
MyClass *my = new MyClass(this);
connect(my, &MyClass::userNameChanged, this, &Widget::userChanged);
my->setUserName("mouze"); // 设置属性的值
qDebug() << "userName1:" << my->getUserName(); // 输出属性的值
// 使用QObject类的setProperty()函数设置属性的值
my->setProperty("userName", "Qt");
// 输出属性的值,这里使用了QObject类的property()函数,它返回值类型为QVariant
qDebug() << "userName2:" << my->property("userName").toString();
//------------------------------
//动态属性
my->setProperty("myValue", 10); // 动态属性,只对该实例有效
qDebug() << "myValue:" << my->property("myValue").toInt();
}
void Widget::userChanged(QString userName)
{
qDebug() << "user changed:" << userName;
}
//main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}