Get the coordinate of specific character in a text givent font and string
-
I have a text (
QString
), and aQFont
that I will use to render this text on the screen. How can I found out either the center coordinate or the bounding rect for a character with indexn
in theQString
? -
@Violet-Giraffe Hi! QFontMetricsF provides the functionality you need.
-
@Wieland, thanks for the quick reply, but I don't see which
QFontMetricsF
method does that (nor do I see any difference from the regularQFontMetrics
, other than using floating-point values). -
@Violet-Giraffe Yeah, it doesn't provide a ready-to-use function for exactly what you want but it has
QRectF boundingRect(const QString &text) const
and with this you can incrementally compute all said coordinates. -
I see! So iterate the text one
QChar
at a time and add up the bounding rects for each one up until the target character? -
@Violet-Giraffe
I think you misunderstood, there's no need for iteration. You can get the character rectangle directly, there's only one additional step to get that rectangle's offset (provided your string doesn't have newlines, tabs and such). For example:QFont font; //< The font you're using. QFontMetrics metrics(font); QString string = "mystring"; int n = 4; QRect left = metrics.boundingRect(string.mid(0, n)); QRect character = metrics.boundingRect(string.at(n)); qint32 centerX = left.width() + (character.width() >> 1); qint32 centerY = left.height() >> 1; // Or character.height() divided by two, they should be the same though
Also you can look up this thread.
-
@kshegunov said:
I think you misunderstood, there's no need for iteration.
It only occurred to me after I went to sleep last night. That's why coding after midnight is not always a great idea :)
@kshegunov said:
qint32 centerY = left.height() >> 1; // Or character.height() divided by two, they should be the same though
Isn't any modern C++ compiler capable of doing that optimization implicitly (with optimizations enabled)?
-
@Violet-Giraffe said:
Isn't any modern C++ compiler capable of doing that optimization implicitly (with optimizations enabled)?
In all probability, yes; it's just a stupid habit. Compilers weren't so smart before, but they are improving by the minute. You can safely replace it with
left.height() / 2
.