Search code examples
c++qtqpainter

QPainter with Qt::AlignCenter does not center text correctly


I want to do a fairly simple drawing where I write a two pieces of text above each other in the center of the circle. My code:

    painter->drawText(QRectF(0, 0, m_iSize, m_iSize), Qt::AlignCenter, m_sAlias + "\n" + m_sCode);

where m_iSize is the size of the circle, m_sAlias is a short text like "R1" and m_sCode is another short text like "31".

The problem is that the above code will draw both lines of text so that they are exactly ONE pixel apart horizontally. And unfortunately it is clearly visible. I suspect the "\n" must do something to it but what I do not know. Nor how to solve it.

My current workaround is to draw the texts separately like this:

    painter->drawText(QRectF(1, 0, m_iSize, m_iSize), Qt::AlignCenter, m_sAlias + "\n");
    painter->drawText(QRectF(0, 0, m_iSize, m_iSize), Qt::AlignCenter, "\n" + m_sCode);

But that is just stupid even though it actully works as expected (I am shifting the top text one pixel to the right).

What am I missing here? If need be I can provide screenshots.

Screenshots:

Wrong (the first one line code), lines are moved by one pixel from each other

Correct (the second two-lines code), lines are aligned correctly


Solution

  • I cannot reproduce this problem, but I am on different system with different default font. It could be that the font you are using specifies 1 px width for the new line character, or Qt is misinterpreting it like so. You should definitely try what happens with another font.

    Anyway, you could use this workaround instead:

    painter->drawText(QRectF(0, 0, m_iSize, m_iSize), Qt::AlignCenter | Qt::AlignTop, m_sAlias);
    painter->drawText(QRectF(0, 0, m_iSize, m_iSize), Qt::AlignCenter | Qt::AlignBottom, m_sCode);
    

    It will render correctly no matter if you are on system that has the new line problem or system that doesn't.