【问题标题】:How to check position of a wheelEvent within text of a QGraphicsTextItem?如何在 QGraphicsTextItem 的文本中检查 wheelEvent 的位置?
【发布时间】:2011-01-10 02:09:49
【问题描述】:
我有一个接受鼠标事件的QGraphicsTextItem 子类(即实现wheelEvent() 方法。
如何检查文本中车轮事件发生的位置?我想获取滚轮事件发生时鼠标指针指向的字母。
顺便说一句:一种可能的解决方案是创建一系列QGraphicsTextItem 对象——每个字母一个。这样每个字母都可以接受它自己的事件,但我放松了所有字距调整和其他排版复杂性。
【问题讨论】:
标签:
qt
mousewheel
qgraphicsview
qgraphicstextitem
【解决方案1】:
要获取鼠标位置,可以使用QWheelEvent::pos。
我没有看到任何 API 可以在项目中的给定 QPointF 处获取字母。不过,您可以尝试使用 QFontMetricsF 获得足够好的近似值,例如
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
如果这不起作用,您可以尝试使用自定义文本项,您自己在其中进行绘画 (QPainter::drawText),这样您就可以更好地控制文本在项目坐标系中的位置。