1

This is the solution I'm working on for this other question. The text needs to be horizontally and vertically centered in the given rect.

void
draw_text_label (QPainter & p, const QString & text, QRectF rect)
{
    // Work in unscaled coordinates (see linked question if you're curious)

    p .save ();
    assert (false == p .transform () .isRotating ());
    rect = p .transform () .mapRect (rect);
    p .resetTransform ();

    // Scale to fit

    set_font_size (p, font_size_to_fit (p, text, rect));

    QRectF text_rect = p .fontMetrics () .tightBoundingRect (text);

    ////////////////////////////
    // this line ALMOST works //
    ////////////////////////////

    text_rect .moveCenter (rect .center ());

    // Draw

    p .translate (text_rect .left (), text_rect .bottom ());

    p .setPen (Qt :: red);
    p .drawText (0, 0, text);
    p .drawRect (0, 0, text_rect .width (), -text_rect .height ());

    p .restore ();
}

Which is called by

void
draw_thingy (QRectF rect)
{
    p .setPen (Qt :: white);
    p .drawRect (rect);

    float m = MARGIN * 0.5;
    draw_text_label (thingy_text, rect .adjusted (m,m,-2*m,-2*m));
}

In summary, the given rect is indicated in white, the text_rect is indicated in red.

enter image description here

As you can see in this test image (link in case the inline image dies), the red rectangle isn't quite centered. This is more than a rounding error.

Why is this happening?

Community
  • 1
  • 1
spraff
  • 32,570
  • 22
  • 121
  • 229

1 Answers1

0

Use the alignment value Qt::AlignCenter in DrawText to center the text in the rect. No rect calculations required.

cppguy
  • 3,611
  • 2
  • 21
  • 36