Important: Please read the Qt Code of Conduct -

QPainter, drawing right aligned text in rectangle cuts the text off

  • Hi,
    I'm using QPainter to draw things into a QImage and then save it to file.
    I need to paint numbers in one specific place on the image, that will be aligned to the right side of another painted element, and it cannot overflow on it.
    I tried calculating the position manually, but it gives me pretty inconsistent results (for example it's ok when drawing a single digit, but then messes up with 2 digits etc).
    The best approach I found is to use painter.drawText function to draw within a QRect on the image canvas and adding Qt::AlignRight flag, this way it's all handled by the painter and will always be aligned to the same exact point.

    It works, however the problem is that on some digits the result is cut off on the right side, and it should not be because it has to be aligned perfectly to that side, there's enough room in the rectangle.
    This is what I'm talking about:
    You can see the 6 is being cut off on the right side.
    This is the rectangle in which I draw the text:
    As you can see there's plenty of space on the right side.

    This is how I draw:

    QImage img(...);
    QPainter painter(&img);
    /* .. */
    QRect rct(img->rect().width() - 800, 0, 510, img->rect().height()); // part of the image
    painter.drawText(rct, Qt::AlignRight, "16");

    Is there any way to prevent it from cutting off? Some right side padding/margin? Or how could I achieve the same result in some other way? I need to have the text right-aligned to a specific (static) point on the image.

Log in to reply