Search code examples
c++drawtextqt5.6

Qt5.6 drawing multi-line text


I want to draw a mutli-line text string with alignment options, do any of the drawText functions in Qt handle this?

I want to pass a string "LINE 1\nLINE 2\nLINE 3\n", with alignment options and draw the text around a specified X,Y point.

So far I'm splitting the string by "\n" then drawing the lines individually.

Also I need to calculate the bounding rectangle required to draw the text so I can create a widget with geometry to contain the text.

I've search for a solution and read on several sites that QPainter::drawText will do this, however when I use drawText with a string containing \n I get one line of text rendered with the \n displayed on the display.


Solution

  • I have decided to write my own routine to manage this, I have an anchor point and I will position the text with alignment on the anchor point.

    The stages required are:

    1. Split text into lines
    2. Work out bounding rectangle using QFontMetrics to determine the size of each line.
    3. Using the specified alignment work out the position of each line relative to the other inside the bounding rectangle.
    4. Draw the text.