Reputation: 549
I'm using QPainter::drawText
to... well... draw some text, but I have an issue when using fonts in italic where the text is written outside of the given QRectF
.
Here is a sample code:
void TestApplication::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QRectF rect(100,100,100,100);
QRectF necessary;
QFont font("Times New Roman", 30);
font.setItalic(true);
painter.setFont(font);
painter.fillRect(rect, QColor(0,255,0));
painter.drawText(rect, Qt::AlignLeft|Qt::AlignVCenter, "ff",&necessary);
}
With this, the output produced is:
As you can see, the first f is written outside of the defined QRectF
. If i write enough text the same will happen in the right hand side. I already tried adding Qt::TextDontClip
to the flags but it produced no effect.
Can somebody help me?
EDIT:
As explained in the answer this is the expected behavior. I've been able to work around it by using leftBearing
(the explanation is in the answer) like so:
void TestApplication::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QRectF rect(20,20,100,100);
QRectF textRect;
QFont font("Times New Roman", 40,0,true);
font.setItalic(true);
painter.setFont(font);
QFontMetrics fontMetrics(font);
textRect = rect.adjusted(-fontMetrics.leftBearing('f'), 0, fontMetrics.leftBearing('f'), 0);
painter.fillRect(rect, QColor(0,255,0));
painter.drawText(textRect, Qt::AlignLeft|Qt::AlignTop, "ff");
}
Producing the expected result:
Upvotes: 5
Views: 3253
Reputation: 27611
The simplest way to deal with this it to reduce the Rect before drawing the text, if the text is italiced: -
QRectF rect(100,100,100,100);
QRectF textRect = rect.adjusted(8, 0, -8, 0);
painter.drawText(textRect, Qt::AlignLeft|Qt::AlignVCenter, "ff",&necessary);
As the Qt documentation states, when passing in the boundingRect rect as the last argument: -
The boundingRect (if not null) is set to the what the bounding rectangle should be in order to enclose the whole text.
So, it's not going to necessarily be bound by the rect you pass in.
Note that the QFontMetrics class allows you to get the boundingRect required for rendering a string: -
QFont font("Times New Roman", 30);
QFontMetrics fontMetrics(font);
fontMetrics.boundingRect("ff");
However, the documentation for QFontMetrics states: -
Note that the bounding rectangle may extend to the left of (0, 0), e.g. for italicized fonts, and that the width of the returned rectangle might be different than what the width() method returns.
So what you are seeing is expected behaviour.
Upvotes: 3