drawText on QGraphicsView::drawForeground

1k Views Asked by At

My code is below.

void MyView::drawForeground(QPainter *painter, const QRectF &rect)
{
    Q_UNUSED(rect);

    painter->save();

    QRectF rt = viewport()->rect();
    painter->setWorldMatrixEnabled(false);

    QString strInfo = "test12345";

    painter->setBrush(Qt::NoBrush);
    painter->setPen(Qt::white);

    painter->setFont(QFont("Segoe UI", 200, QFont::Bold));

    QFontMetrics fm(painter->font());
    int fmWidth = fm.width(strInfo, strInfo.length());
    int fmHeight = fm.height();

    painter->drawRect(rt);
    painter->drawText(10, 10, fmWidth, fmHeight, Qt::AlignCenter, strInfo);
    painter->drawRect(10, 10, fmWidth, fmHeight);
    painter->setWorldMatrixEnabled(true);
    painter->restore();
}

result image

QfontMetrics does not seem to return the correct size. What's wrong with my code?

I do not know what to do anymore.

QFontMetrics returns the size of the white rectangle of the attached image, but the actual Text is drawn small.

1

There are 1 best solutions below

0
On

Regardless of QPainter::setWorldMatrixEnabled(false), QPainter::drawText() behaves as a scene coordinate.