Search code examples
qtqtwidgets

How to position a QStaticText by its baseline?


How can I achieve baseline positioning for a QStaticText object?

For regular text, it's simple: In QPainter::drawText(position, text), the position.y coordinate refers to the baseline.


Solution

  • It turned out that drawStaticText positions the text at the baseline, but offsetting the y-coordinate by the font's ascent.

    This is meant by top of the font in the documentation.

    Minimal demo:

    #include <QApplication>
    #include <QWidget>
    #include <QPainter>
    #include <QPaintEvent>
    #include <QStaticText>
    
    class Window: public QWidget
    {
    public:
        void paintEvent(QPaintEvent*) override
        {
            QPainter painter(this);
            const int y = 20;
    
            painter.fillRect(0, y, 200, 1, Qt::black);
    
            // These all share the same baseline
            painter.drawStaticText(10, y, QStaticText("Üg."));
            painter.drawStaticText(26, y, QStaticText("."));
            painter.drawText(29, y + QFontMetrics(QApplication::font()).ascent(), ".");
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        Window win;
        win.show();
        return app.exec();
    }
    

    Output:

    enter image description here