动态属性
- 在标准C++中,为了保证封装性,我们经常声明一个私有变量,然后声明两个公有函数,即set函数和get函数。
- 在Qt中我们可以使用宏Q_PROPERTY()宏来实现这些。一个属性可以使用常规函数QObject::property()和QObject::setProperty()进行读写,不用知道属性所在类的任何细节,除了属性的名字。
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])
示例:
1.新建桌面应用程序TestProperty,父类QWidget,其他采用默认。 2.右键单击项目添加自定义类MyPropertyClass,父类QObject. 3.mypropertyclass.h文件中Q_OBJECT下方声明属性宏:
mypropertyclass.h
#ifndef MYPROPERTYCLASS_H
#define MYPROPERTYCLASS_H
#include <QObject>
class MyPropertyClass : public QObject{
Q_OBJECT
Q_PROPERTY(QString Salary READ Salary WRITE setSalary NOTIFY SalaryChanged)
public:
explicit MyPropertyClass(QObject *parent = nullptr);
QString Salary() const;
void setSalary(QString salary);
signals:
void SalaryChanged(QString str);
public slots:
private:
QString m_salary;
};
#endif
mypropertyclass.cpp
#include "mypropertyclass.h"
MyPropertyClass::MyPropertyClass(QObject *parent) : QObject(parent){
}
QString MyPropertyClass::Salary() const{
return m_salary;
}
void MyPropertyClass::setSalary(QString salary) {
m_salary = salary;
emit SalaryChanged(m_salary);
}
?
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void salaryChanged(QString str);
private:
Ui::Widget *ui;
};
#endif
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "mypropertyclass.h"
#include <QDebug>
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
ui->setupUi(this);
MyPropertyClass *mypC = new MyPropertyClass;
MyPropertyClass *mypC2 = new MyPropertyClass;
connect(mypC, SIGNAL(SalaryChanged(QString)), this, SLOT(salaryChanged(QString)));
mypC->setSalary("20000");
qDebug()<< "获取当前薪资: " << mypC->Salary();
QObject *obj = mypC;
qDebug() << "obj第一次读取动态属性: " << obj->property("Salary").toString();
obj->setProperty("Salary", "30000");
qDebug() << "obj第二次读取动态属性: " << obj->property("Salary").toString();
qDebug() << "mypC2读取动态属性: " << mypC2->Salary();
}
Widget::~Widget(){
delete ui;
}
void Widget::salaryChanged(QString str){
qDebug()<<"新的薪资: " << str;
}
? main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[]){
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
|