思路:
继承QLabel,重新绘制。
代码:
h文件
#ifndef VLABEL_H
#define VLABEL_H
#include<QPainter>
#include<QLabel>
#include<QDebug>
class vLabel : public QLabel
{
Q_OBJECT
public:
explicit vLabel(QWidget* parent = NULL);
virtual ~vLabel();
//绘制文字
void drawText(QPainter *painter);
protected:
void paintEvent(QPaintEvent *);
int fontW;
int fontH;
};
#endif // VLABEL_H
cpp文件
#pragma execution_character_set("utf-8")
#include "vlabel.h"
vLabel::vLabel(QWidget *parent): QLabel(parent)
{
}
vLabel::~vLabel()
{
}
void vLabel::drawText(QPainter *painter)
{
painter->save();
painter->setBrush(Qt::NoBrush);
painter->translate(width()>>1,height()>>1);
painter->rotate(-90.0);//旋转-90度
QFontMetrics fm(this->font());
fontW = fm.width(this->text());
fontH = fm.height();
this->setFixedHeight(fontW);
this->setFixedWidth(fontH*2);
painter->drawText(0-fontW/2,0+fontH/2,this->text());
painter->restore();
}
void vLabel::paintEvent(QPaintEvent *)
{
//绘制准备工作,启用反锯齿
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
//绘制文字
drawText(&painter);
}