1、QLabel设置图像有两种方法
(1) void setPicture(const QPicture &);
(2) void setPixmap(const QPixmap &);
QPicture和QPixmap都是继承于QPaintDevice,它们都可以通过加载图片的方式获取:bool load(QIODevice *dev, const char *format = nullptr),也可以通过QPainter上绘制。
2、QPainter绘制文本换行显示
void drawText(const QRect &r, int flags, const QString &text, QRect *br = nullptr)
在设置第二个参数flags时,使用Qt::TextWrapAnywhere 即可使文本换行显示。
3、核心代码
(1) LabelEx.h
#ifndef LABELEX_H
#define LABELEX_H
#include <QLabel>
const QString kText = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
class LabelEx : public QLabel
{
Q_OBJECT
public:
explicit LabelEx(QWidget *parent = nullptr);
~LabelEx();
protected:
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
};
#endif // LABELEX_H
(2) LabelEx.cpp
#include "LabelEx.h"
#include <qpainter.h>
LabelEx::LabelEx(QWidget *parent) : QLabel(parent)
{
}
LabelEx::~LabelEx()
{
}
void LabelEx::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::TextAntialiasing);
painter.fillRect(rect(), QColor(255, 160, 160));
painter.drawText(rect(), Qt::AlignLeft |Qt::AlignTop |Qt::TextWrapAnywhere, kText);
}
(3) LabelTestDlg.h
#ifndef LABELTESTDLG_H
#define LABELTESTDLG_H
#include <QDialog>
#include "LabelEx.h"
class LabelTestDlg : public QDialog
{
Q_OBJECT
public:
LabelTestDlg(QWidget *parent = nullptr);
~LabelTestDlg();
private:
void init();
private:
QLabel *m_lb1 = nullptr;
QLabel *m_lb2 = nullptr;
LabelEx *m_lb3 = nullptr;
};
#endif // LABELTESTDLG_H
(4) LabelTestDlg.cpp
#include "LabelTestDlg.h"
#include <qpicture.h>
#include <qpainter.h>
#include <qboxlayout.h>
LabelTestDlg::LabelTestDlg(QWidget *parent)
: QDialog(parent)
{
init();
}
LabelTestDlg::~LabelTestDlg()
{
}
void LabelTestDlg::init()
{
setWindowTitle("Label测试");
m_lb1 = new QLabel(this);
m_lb2 = new QLabel(this);
m_lb3 = new LabelEx(this);
m_lb1->setFixedSize(150, 300);
m_lb2->setFixedSize(150, 300);
m_lb3->setFixedSize(150, 300);
QPicture pic;
QPainter painter1(&pic);
painter1.fillRect(m_lb1->rect(), QColor(160, 255, 160));
painter1.drawText(m_lb1->rect(), Qt::AlignLeft |Qt::AlignTop |Qt::TextWrapAnywhere, kText);
m_lb1->setPicture(pic);
QPixmap pix(m_lb2->size());
pix.fill(QColor(160, 160, 255));
QPainter painter2(&pix);
painter2.drawText(m_lb2->rect(), Qt::AlignLeft |Qt::AlignTop |Qt::TextWrapAnywhere, kText);
m_lb2->setPixmap(pix);
QHBoxLayout *lay = new QHBoxLayout(this);
lay->setContentsMargins(16, 16, 16, 16);
lay->setSpacing(16);
lay->addWidget(m_lb1);
lay->addWidget(m_lb2);
lay->addWidget(m_lb3);
}