PDA

View Full Version : Get location in String from pixel-position



tuli
5th May 2021, 08:07
Hi,

I paint a QString onto a widget, and the user clicks somewhere into the painted string. I have the QPoint of the mouse click, the painted string e.g. QString = "123456789", the font used and a QFontMetrics.
How can I now find at what position / what character the user placed the mouseclick?


I could use a monospaced font and do pos.x() / metrics.averageCharWidth().
I could also iterate over the string, call metrics.width(char) on ever successive char, and then check when I hit pos.y().


The first obv doesnt support non-monospaced fonts, the second looks inefficient, is there a better way? I mean, TextEdits have to do it in some way too right.


Thanks!

ChrisW67
5th May 2021, 08:17
Why are you reinventing the wheel?

tuli
5th May 2021, 08:37
Because it's a complex custom widget. I cant just use a textbox. Or what do you mean?