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])
下面是一些关于标记的简单介绍:
下面是一个关于属性使用的简单示例:
.h文件中的代码:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QVBoxLayout>
class Widget : public QWidget
{
Q_OBJECT
Q_PROPERTY(int testProperty READ testProperty WRITE setTestProperty NOTIFY testPropertyChanged)
public:
Widget(QWidget *parent = 0);
~Widget();
private:
int m_TestProperty;
int testProperty() const;
void setTestProperty(int);
signals:
void testPropertyChanged(int);
};
// ---------------------------------------------------------------------
class TestPropertyWidget : public QWidget
{
Q_OBJECT
public:
TestPropertyWidget(QWidget *parent = nullptr);
~TestPropertyWidget();
Widget *getMainWidget(void){
return m_Widget;
}
private:
Widget *m_Widget = nullptr;
};
#endif // WIDGET_H
.cpp中的代码
#include "widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_TestProperty = 10;
}
Widget::~Widget()
{
}
int Widget::testProperty() const
{
return m_TestProperty;
}
void Widget::setTestProperty(int property)
{
m_TestProperty = property;
emit testPropertyChanged(property);
}
// ---------------------------------------------------------------------
TestPropertyWidget::TestPropertyWidget(QWidget *parent)
:QWidget(parent)
{
QVBoxLayout *m_MainLayout = new QVBoxLayout(this);
m_Widget = new Widget;
m_MainLayout->addWidget(m_Widget);
QObject::connect(m_Widget, &Widget::testPropertyChanged, [&](int testPropertyValue)->void{
qDebug() << "TestPropertyChanged " << testPropertyValue;
});
}
TestPropertyWidget::~TestPropertyWidget()
{
}
main函数中的调用:
#include "widget.h"
#include <QApplication>
#include <QObject>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TestPropertyWidget w;
w.setGeometry(100, 100, 800, 600);
w.show();
qDebug() << w.getMainWidget()->property("testProperty").toInt();
w.getMainWidget()->setProperty("testProperty", 20);
return a.exec();
}
程序的最终输出结果为
10
TestPropertyChanged 20
首先打印属性“testProperty”中的值,然后为改变属性中的值为20,属性发生变化时发送信号通知,在接收信号的处理函数中打印“TestPropertyChanged 20”