QtApplets-自定义控件-4-属性研究

Posted DreamLife.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QtApplets-自定义控件-4-属性研究相关的知识,希望对你有一定的参考价值。

QtApplets-自定义控件-4-属性研究

​ 这一篇我们研究研究自定控件中属性部分。也终于要添加我们自己的代码了。先看下演示效果吧。这里我搞了一个名字叫做testID的属性,他对应的读函数为getTestID写函数为setTestID


关键字: Q_PROPERTY属性自定义设置获取

1 声明一个自定义的属性

​ 这里我们需要用到一个关键宏Q_PROPERTY,看看官方对这个宏的描述

This macro is used for declaring properties in classes that inherit QObject. Properties behave like class data members, but they have additional features accessible through the Meta-Object System.

简单翻译一下:

这个宏用于在继承QObject的类中声明属性,属性的行为类似于数据成员,但是它们有通过元对象系统访问的附加特性。

  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])

The property name and type and the READ function are required. The type can be any type supported by QVariant, or it can be a user-defined type. The other items are optional, but a WRITE function is common. The attributes default to true except USER, which defaults to false.

简单翻译一下:

属性名、类名和READ函数是必须的,类名可以是QVariant支持的任何类型,也可以是用户定义的类型,其他项目是可选,但是WRITE函数是常见,除了USER,其他属性默认为true,UESR默认为false

Q_PROPERTY(QString title READ title WRITE setTitle USER true)

​ 所以,按照这流程,我的代码如下

Q_PROPERTY(int testID READ getTestID WRITE setTestID)

​ 同时需要声明一个变量,一个读函数和一个写函数,如下

    int testID = 1;
    int getTestID();
    void setTestID(int temp);

2 实现

​ 实现其实也很简单,这里为了更加直观,我用一个QLabel来显示我们的修改的值,代码如下,我就直接全部复制了

#include "customcontrol.h"

CustomControl::CustomControl(QWidget *parent) :
    QWidget(parent)
{
    m_label = new QLabel(this);
    m_label->setGeometry(0,0,100,20);
}

int CustomControl::getTestID()
{
    return testID;
}

void CustomControl::setTestID(int temp)
{
    testID = temp;
    m_label->setGeometry(0,0,100,20);
    m_label->setStyleSheet("color: rgb(255, 255, 0);font: 11pt '黑体';");
    m_label->setText(QString::number(testID,10));
    update();
}

效果如开头显示所示。

☞ 源码

源码链接:GitHub仓库自取

使用方法:☟☟☟

以上是关于QtApplets-自定义控件-4-属性研究的主要内容,如果未能解决你的问题,请参考以下文章

QtApplets-自定义控件-7-属性研究

QtApplets-自定义控件-6-属性研究(未成功)

QtApplets-自定义控件-1-工程代码分析

QtApplets-自定义控件-8-自定义图标

QtApplets-自定义控件-2-插件代码分析

QtApplets-自定义控件-3-插件部署问题