Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Does QFontMetricsF ::width() equals painter.drawText() width?



  • Hi,
    I want to use QPainter to draw text and make sure the text center at the origin of the coordinate axis

    
    QFontMetricsF fm(m_graduateFont);
    qDebug() << "m_graduateFont" << m_graduateFont;
    qDebug() << "fm" << fm.size(Qt::TextSingleLine, "0");
    qDebug() << "fm" << fm.size(Qt::TextSingleLine, "11");
    qDebug() << "fm" << fm.size(Qt::TextSingleLine, "100");
    qDebug() << "fm" << fm.boundingRect(QRect(), Qt::AlignCenter, "100");
    double fontHeigth = fm.height();
    double textWidth = fm.width(num);
    painter.save();
    painter.setFont(m_graduateFont);
    painter.drawText(QPointF(- textWidth * .5, fontHeigth * .5), num);
    
    painter.setPen(Qt::red);
    painter.drawLine(-textWidth * .5, 0, textWidth * .5, 0);
    painter.drawLine(0, -fontHeigth * .5, 0, fontHeigth * .5);
    painter.restore();
    

    but it seems they do not match, did I forget something?

    3.PNG

    thanks.


Log in to reply