QT 属性系统

#ifndef MYCLASS_H
#define MYCLASS_H

#include 

class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString userName READ getUserName WRITE setUserName NOTIFY userNameChanged) //注册属性userName
public:
    explicit MyClass(QObject *parent = 0);
    //实现READ读函数
    QString getUserName() const
    {
        return m_userName;
    }
    //实现write写函数
    void setUserName(QString userName)
    {
        m_userName = userName;
        //当属性值改变时发射该信号
        emit userNameChanged(userName);
    }

signals:
    void userNameChanged(QString);      //声明NOTIFY通知消息
public slots:
private:
    QString m_userName;     //私有变量,存放userName属性的值
};

#endif // MYCLASS_H
#include "widget.h"
#include "ui_widget.h"
#include "myclass.h"
#include 
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    MyClass* my = new MyClass(this);        //  创建MyClass类实例
    connect(my,&MyClass::userNameChanged,this, &Widget::userChanged);
    my->setUserName("yafei");               //  设置属性的值
    //使用QObject类的setProperty函数设置属性的值
    qDebug()<<"userName1:"<getUserName();
    my->setProperty("userName", "linux");
    //输出属性的值,这里使用了QObject类的property函数,他返回的值类型为QVariant
    qDebug()<<"userName2:"<property("userName").toString();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::userChanged(QString userName)
{
    qDebug()<<"user changed:"<

 

你可能感兴趣的:(QT 属性系统)