Widget::Widget(QWidget *parent)
: QWidget(parent)
{
auto font = this->font();
font.setPixelSize(30);
setFont(font);
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setPen(Qt::red);
painter.setFont(this->font());
QString s = "会须一饮sf0.三百杯eso.,";
QString str = s.split("", Qt::SkipEmptyParts).join("\n");
painter.drawText(rect(), Qt::AlignCenter ,str);
auto r = painter.boundingRect(rect(), Qt::AlignCenter ,str);
painter.drawRect(r);
painter.setPen(Qt::cyan);
QSize size = getVerticalTextBoundingRect(str);
painter.drawRect(QRect(r.x(),r.y(),size.width(),size.height()));
}
QSize Widget::getVerticalTextBoundingRect(const QString & str)
{
QFontMetrics fm(font());
QStringList lines = str.split("\n");
int maxWidth = 0;
int totalHeight = 0;
for (const QString &line : lines)
{
int width = fm.horizontalAdvance(line);
if (width > maxWidth)
{
maxWidth = width;
}
totalHeight += fm.height();
totalHeight += fm.leading();
}
totalHeight -= fm.descent();
return QSize(maxWidth, totalHeight);
}
可见其结果基本和 QPainter 的 boundingRect() 是一致的。
相关博文: