Qt每天一个小技巧之setProperty 设置属性功能

说好的计划,就要实现,今年我要把吹过的牛皮,设定的计划,统统给圆了。

打开Qt帮助文档,我们接着看到了这个函数:

QList<QByteArray> dynamicPropertyNames() const

这个函数的目的就是获取到动态属性的名字,那我们相关运用到上面是那些呢。

与其相关联就是下面函数了:

QVariant property(const char *name) const
bool setProperty(const char *name, const QVariant &value)

一个是获取属性,一个是设置属性。那我们一般如何用这个呢,好多情况在qss中配合使用。

首先看下代码:

void MainWindow::setPropertA()
{
    QPushButton *button = new QPushButton;
    button->setProperty("flat",true);
    QVariant isflat = button->property("flat");
    qDebug() << isflat << endl;
}

我们可以设置一个属性,然后在找到对应的属性值。

我们运用到qss中,来看下效果吧。

首先我们界面布局如下

对应的qss表写如下:

QLineEdit#lineEdit
{
	background:yellow;
}

#lineEdit[required = true]
{
	background:red;
}

 在改变属性按钮写下如下代码:

void MainWindow::on_pushButton_clicked()
{
    ui->lineEdit->setProperty("required",true); //设置为true
    ui->lineEdit->style()->polish(ui->lineEdit);
}

运行程序后,点击按钮后,就会变成红色。

 

 dynamicPropertyNames的使用

我们在按钮下,写下代码:

void MainWindow::on_pushButton_2_clicked()
{
    QList<QByteArray> names = ui->lineEdit->dynamicPropertyNames();
    for(auto name : names)
    {
        qDebug() << name << endl;
    }
}

我们可以发现上面有我们设置的名字。

有关这个属性使用可以看我这个博客,之前写过一个功能,希望大家喜欢:

传送门:https://blog.csdn.net/weixin_42126427/article/details/106716048 

下面是cpp整体的代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QDebug>
#include <QStyle>
#include <QList>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setPropertA();
}

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

void MainWindow::setPropertA()
{
    QPushButton *button = new QPushButton;
    button->setProperty("flat",true);
    QVariant isflat = button->property("flat");
    qDebug() << isflat << endl;
}

void MainWindow::on_pushButton_clicked()
{
    ui->lineEdit->setProperty("required",true); //设置为true
    ui->lineEdit->style()->polish(ui->lineEdit);
}



void MainWindow::on_pushButton_2_clicked()
{
    QList<QByteArray> names = ui->lineEdit->dynamicPropertyNames();
    for(auto name : names)
    {
        qDebug() << name << endl;
    }
}

 

  • 23
    点赞
  • 81
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值