QSS中使用qproperty-<property name>设置Qt对象属性值的例子

对于在QSS中设置Qt对象属性值,QSS官方文档有如下描述

但在实际使用时,使用qproperty-pixmap这种方式设置属性时遇到过一些问题,特在此处总结一下,如下面的例程:

mylabel.h

#ifndef MYLABEL_H
#define MYLABEL_H

#include <QLabel>

class MyLabel : public QLabel
{
    Q_OBJECT
    //经测试,QPixmap类型必须配置WRITE,否则编译时会出现,如下错误:
    //error: no match for 'operator!=' (operand types are 'QPixmap' and 'QPixmap')
    Q_PROPERTY(QPixmap face MEMBER m_face WRITE setFace)

    //QString, int等,不需要配置WRITE也可以正常使用
    Q_PROPERTY(QString name MEMBER m_name)
public:
    explicit MyLabel(QWidget *parent = 0);

    void setFace(const QPixmap &pixmap);

protected:
    void paintEvent(QPaintEvent *event);

private:
    QPixmap m_face;
    QString m_name;
};

#endif // MYLABEL_H

mylabel.cpp

#include "mylabel.h"
#include <QPainter>

MyLabel::MyLabel(QWidget *parent)
    : QLabel(parent)
{

}

void MyLabel::setFace(const QPixmap &pixmap)
{
    m_face=pixmap;
}

void MyLabel::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.drawPixmap(0, 0, width(), height(), m_face);
    QPen pen=p.pen();
    pen.setColor(Qt::red);
    p.setPen(pen);
    QFont font=p.font();
    font.setPixelSize(25);
    font.setBold(true);
    p.setFont(font);
    p.drawText(QRect(0, 0, width(), height()), Qt::AlignCenter, m_name);
}

mainwidget.h

#ifndef MAINWIDGET_H
#define MAINWIDGET_H

#include <QWidget>

namespace Ui {
class MainWidget;
}

class MainWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MainWidget(QWidget *parent = 0);
    ~MainWidget();

private slots:
    void on_buttonSetup_clicked();

private:
    Ui::MainWidget *ui;
};

#endif // MAINWIDGET_H

mainwidget.cpp

#include "mainwidget.h"
#include "ui_mainwidget.h"

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);
}

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

void MainWidget::on_buttonSetup_clicked()
{
    this->setStyleSheet(ui->textStyleSheet->toPlainText());
}

运行效果(点击Setup按钮后的运行效果):

(-------------完-----------)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值