自定义QLabel 控件

话不多说,直接效果,这一贯是自己的风格,再多的话语,不如直接干货。

自定义QLabel 控件

上图为最终效果:继承QLabel 类,进行重绘,适配各种分辨率。本实例只是抛砖引玉,烦请大神让行。

#ifndef PICTURELABELWIDGET_H
#define PICTURELABELWIDGET_H


#include <QWidget>
#include <QPainter>
#include <QDebug>
#include <QLabel>

//图标 显示

class PictureLabelWidget : public QLabel
{
    Q_OBJECT
public:
    explicit PictureLabelWidget(QWidget *parent = nullptr);

signals:

public slots:

public:
   void picture_label_init(QString color,QString name,QString contex,QString ico);//color:主背景色 name:显示的标题 contex:设置内容  ico:图标路径
   void label_contex(QString contex);//显示内容设置
private:

    QString  nameText; //题目
    QString  contexText; //内容

    QString  backLightColor; //背景颜色
    QString  icoPath; //显示图标路径
protected:
    virtual void paintEvent(QPaintEvent *event);




};

#endif // PICTURELABELWIDGET_H

#include "picturelabelwidget.h"

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

    this->setAttribute(Qt::WA_DeleteOnClose,true); //析构后完成内存的释放
}


void PictureLabelWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    QPen pen;

    //pen.setColor(QColor(92,114,137));
    pen.setWidth(1);
    pen.setStyle(Qt::NoPen);

    painter.setPen(pen); //设置画笔形式
    painter.setBrush(QBrush(QColor(backLightColor),Qt::SolidPattern)); //设置画刷形式
    painter.drawRect(0,0,this->width(),this->height());

    pen.setStyle(Qt::SolidLine);
    pen.setColor(QColor(0, 0, 0));

    QFont font;
    font.setPointSize(12);
    font.setBold(false);//粗体
    painter.setFont(font);
    painter.setPen(pen);
    painter.drawText(this->width()*0.05,0,this->width(),this->height(),Qt::AlignVCenter |Qt::AlignLeft,nameText);
    font.setBold(true);//粗体
    font.setPointSize(14);
    painter.setFont(font);
    painter.setPen(pen);
    painter.drawText(this->width()*0.5,0,this->width(),this->height(),Qt::AlignVCenter |Qt::AlignLeft,contexText);


    QPixmap pix;
    pix.load(icoPath);
    //qDebugInfo() <<this->height()<<pix.height() <<hScale;
    pix = pix.scaled(this->size()*0.8,Qt::KeepAspectRatio, Qt::SmoothTransformation);

    painter.drawPixmap(this->width()-pix.width()-this->width()*0.05,this->height()*0.15,pix.width(),pix.height(),pix);

}
void PictureLabelWidget::label_contex(QString contex)
{
    contexText = contex;
    this->update();
}
void PictureLabelWidget::picture_label_init(QString color,QString name,QString contex,QString ico)
{
    backLightColor = color;
    nameText = name;
    contexText = contex;
    icoPath = ico;
    this->update();
}

 

父类应用如下:

 

自定义QLabel 控件 

上一篇:Java基础编程技巧汇总


下一篇:SpringBoot整合Shiro(一)