如上图所示,是一张四周带阴影的图片,且右侧还有一个尖尖的箭头,但如果直接用样式表贴图,就会产生四周变形的问题。如下图所示:
为了防止图像变形,且能随着内容拉伸,可以用九宫格画。
九宫格原理:
就是把图片分割成 9 个部分
- 4 个角的大小不变
- 左、右部分宽度不变,进行垂直拉伸或平铺绘制
- 上、下部分高度不变,进行水平拉伸或平铺绘制
- 中间部分进行拉伸或平铺绘制
#ifndef JIUGONGGE_H
#define JIUGONGGE_H
#include <QWidget>
#include <QPushButton>
#include <QLayout>
#include <QObject>
class JiuGongGe : public QWidget
{
Q_OBJECT
public:
explicit JiuGongGe(QWidget *parent = nullptr);
void setText(QString text);
protected:
void paintEvent(QPaintEvent * event);
private slots:
void Slot_addText();
private:
QPixmap m_bgPixmap;
QString m_strText;
};
#endif // JIUGONGGE_H
#include "jiugongge.h"
#include <QPainter>
#include <QtMath>
#include <QDebug>
JiuGongGe::JiuGongGe(QWidget *parent) : QWidget(parent)
{
m_bgPixmap = QPixmap("D:/XjQtWork/config/warning_bg.png");
QPushButton * button = new QPushButton("添加一句");
connect(button,SIGNAL(clicked(bool)),this,SLOT(Slot_addText()));
QVBoxLayout * layout = new QVBoxLayout(this);
layout->addStretch();
layout->addWidget(button);
}
void JiuGongGe::setText(QString text)
{
m_strText.append(text);
update();
}
void JiuGongGe::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QFont font;
font.setPixelSize(15);
painter.setFont(font);
QFontMetrics fm(font);
int textWidth = fm.width(m_strText);
int textHeight = fm.height();
int width = rect().width() - 50; //左右间距
int row = 1;
if(textWidth > width)
row = qCeil(textWidth / width);
textHeight = row * 22 + 50;
//上面三个部分
painter.drawPixmap(QRect(0, 0, 25, 50),m_bgPixmap, QRect(0, 0, 25, 50));
painter.drawPixmap(QRect(25, 0, this->width() - 50, 50),m_bgPixmap, QRect(25, 0, 25, 50));
painter.drawPixmap(QRect(this->width() - 25, 0, 25, 50),m_bgPixmap, QRect(m_bgPixmap.width() - 25, 0, 25, 50));
//中间三个部分
painter.drawPixmap(QRect(0, 50, 25, textHeight - 75),m_bgPixmap, QRect(0, 50, 25, 5));
painter.drawPixmap(QRect(25,50, this->width() - 50, textHeight - 75),m_bgPixmap, QRect(25, 50, 25, 5));
painter.drawPixmap(QRect(this->width() - 25, 50, 25, textHeight - 75),m_bgPixmap, QRect(m_bgPixmap.width() - 25, 50, 25, 5));
//下面三个部分
painter.drawPixmap(QRect(0, textHeight - 25, 25, 25),m_bgPixmap, QRect(0, m_bgPixmap.height() - 25, 25, 25));
painter.drawPixmap(QRect(25,textHeight - 25, this->width() - 50, 25),m_bgPixmap, QRect(25, m_bgPixmap.height() - 25, 25, 25));
painter.drawPixmap(QRect(this->width() - 25, textHeight - 25, 25, 25),m_bgPixmap, QRect(m_bgPixmap.width() - 25, m_bgPixmap.height() - 25, 25, 25));
//画文本
painter.save();
painter.setPen(Qt::black);
painter.drawText(QRect(30, 20, this->width() - 50,row * 25),Qt::AlignVCenter | Qt::AlignLeft | Qt::TextWordWrap, m_strText);
painter.restore();
}
void JiuGongGe::Slot_addText()
{
setText("这是一条提示呀呀呀呀");
}
效果如下: