mypropertyclass.h
#ifndef MYPROPERTYCLASS_H
#define MYPROPERTYCLASS_H
#include <QObject>
class MyPropertyClass : public QObject
{
//使用信号和槽
Q_OBJECT
//使用动态属性
Q_PROPERTY(QString mask READ mask WRITE setMask NOTIFY maskChanged)
public:
explicit MyPropertyClass(QObject *parent = nullptr);
QString mask()const; //读属性 READ
void setMask(QString strMaskNum); //写属性 WRITE setMask
signals:
void maskChanged(QString str); //属性改变时发送的信号 NOTIEY
private:
QString m_mask; //保存属性的值
};
#endif // MYPROPERTYCLASS_H
mypropertyclass.cpp
#include "mypropertyclass.h"
MyPropertyClass::MyPropertyClass(QObject *parent) : QObject(parent)
{
}
QString MyPropertyClass::mask() const
{
return m_mask;
}
void MyPropertyClass::setMask(QString strMaskNum)
{
//设置属性
m_mask = strMaskNum;
//发送信号
emit maskChanged(strMaskNum);
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void maskChanged(QString str);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "QDebug"
#include "mypropertyclass.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
MyPropertyClass *mypC = new MyPropertyClass;
connect(mypC,SIGNAL(maskChanged(QString)),this,SLOT(maskChanged(QString)));
mypC->setMask("1200");
qDebug() << mypC->mask();
QObject* obj = mypC;
//通过obj进行属性读取
qDebug() << obj->property("mask").toString();
//通过obj设置属性
obj->setProperty("mask","5000");
}
Widget::~Widget()
{
delete ui;
}
void Widget::maskChanged(QString str)
{
qDebug() << "新的属性已改成"<<str;
}
main
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}