Question

I have a QGraphicsTextItem subclass that accepts mouse events (i.e. implements wheelEvent() method.

How can I check on which position within the text the wheel event happened? I would like to get the letter that the mouse pointer pointed at when the wheel event happened.

BTW: one possible solution is to create a series of QGraphicsTextItem objects -- one for every letter. This way each letter can accept it's own events, but I loose all the kerning and other typesetting sophistication.

Was it helpful?

Solution

To get the mouse position, you can use QWheelEvent::pos.

I don't see any API to get the letter at a given QPointF in the item. you could try to get a maybe good enough approximation using QFontMetricsF though, doing something like

 const int wx = wheelEvent->pos().x(); //might have to map to item coordinates
 const qreal leftX = item->boundingRect().left();
 const QFontMetricsF fm( item->font() );
 int pos = 0;
 while ( fm.width( text.left( pos ) - leftX < wx )
      pos++; //could be optimized by something binary-search-like

If that doesn't work out, you could try with a custom text item where you do the painting (QPainter::drawText) yourself, so you have more control over the positioning of the text in the item's coordinate system.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top