0

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.

  • It works for me correctly: https://imgur.com/a/vsNDQqO with Qt 5.11.1 – eyllanesc Jul 09 '18 at 12:53
  • I can not see what went wrong. Are there any other elements related to QPainter :: drawText? – DaeHee.Lim Jul 09 '18 at 12:58
  • As I said I used your code and did not find any problem, maybe some part that does not show your code generates that problem, could share your entire project through github or similar – eyllanesc Jul 09 '18 at 13:00
  • Thank you for your kind reply. I need to debug again one by one. – DaeHee.Lim Jul 09 '18 at 13:03
  • I removed my scene and replaced it with the default QGraphicsScene. It has exactly. Perhaps it is affected by the size of the scene. remove "fitInView", QFontMetrics returns the correct value. – DaeHee.Lim Jul 09 '18 at 13:17
  • If you provide a decent [mcve] you could try to help. – eyllanesc Jul 09 '18 at 13:20

1 Answers1

0

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241