QPainter绘制字体显示框,字体可随窗口自动适应。

QPainter绘制字体显示框,字体可随窗口自动适应。使用QPainter绘制的显示控件,核心使用scale来进行比例发达缩小,使用translate来偏移坐标系。效果如下:

在这里插入图片描述初始
在这里插入图片描述
对窗口进行拉伸字体大小,边框线框随着拉伸变大变小。

头文件.h

#ifndef DISPLAYFRAME_H
#define DISPLAYFRAME_H

#include <QWidget>
#include <QColor>
#include <QPainter>

class DisplayFrame : public QWidget
{
    Q_OBJECT
public:
    explicit DisplayFrame(QWidget *parent = nullptr);
    ~DisplayFrame();
    void SetText(QString str0,QString str1);
protected:
    void    paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
private:
    QString titleStr;
    QString textStr;

signals:

public slots:
};

#endif // DISPLAYFRAME_H

源文件cpp

#include "displayframe.h"

DisplayFrame::DisplayFrame(QWidget *parent) : QWidget(parent)
{


}

DisplayFrame::~DisplayFrame()
{

}

void DisplayFrame::paintEvent(QPaintEvent *event)
{

    double width = this->width();
    double height = this->height();
    double side = qMin(width, height);
    double radius = 100;
    double scale = side/100;
    double linewith = side/10;
    QColor bgColor = Qt::black;
    QColor penColor =  Qt::green;
    QColor titleColor = Qt::white;
    QColor textColor = Qt::red;
    QFont font;

    //基本绘图
    QPainter   Painter(this);//创建QPainter对象
    Painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    //绘制背景
    if (bgColor != Qt::transparent) {
        Painter.setPen(Qt::NoPen);
        Painter.fillRect(this->rect(), bgColor);
    }
    //设置画笔 绘制边框
    QPen    pen;
    pen.setWidth(linewith); //线宽
    pen.setColor(penColor); //划线颜色
    pen.setStyle(Qt::SolidLine);//线的类型,实线、虚线等
    pen.setCapStyle(Qt::FlatCap);//线端点样式
    pen.setJoinStyle(Qt::BevelJoin);//线的连接点样式
    Painter.setPen(pen);
    Painter.drawRect(this->rect()); //只填充定义的渐变区域
    //偏移坐标
    Painter.translate(linewith,linewith);
    Painter.scale(scale, scale);
    Painter.save();
    //绘制标题
    font.setPixelSize(20);
    Painter.setFont(font);
    Painter.setPen(titleColor);
    QRect   titleRect(0,0,radius,radius/4); //中间区域矩形框
    Painter.drawText(titleRect,Qt::AlignLeft,titleStr);
    //绘制文本
    font.setPixelSize(40);
    Painter.setFont(font);
    Painter.setPen(textColor);
    QRectF   textRect(radius/2,radius/4,radius,radius); //中间区域矩形框
    Painter.drawText(textRect,Qt::AlignLeft,textStr);
}
void DisplayFrame::SetText(QString titleStr,QString textStr)
{
   this->titleStr = titleStr;
   this->textStr = textStr;
}
示例下载:
https://download.csdn.net/download/FQJ19950804/19135056






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值