在QT图形视图框架中,想要Item响应获得焦点事件,首先需要设置本Item可以获得焦点
一般Item可以使用
setFlag(QGraphicsItem::ItemIsFocusable);
来使Item可以获取焦点事件,但是针对QGraphicsTextItem,它有一个另外的设置方法,首先来看这个方法的函数原型
void setTextInteractionFlags(Qt::TextInteractionFlags flags)
帮助文档中对这个方法是这样解释的:
Sets the flags flags to specify how the text item should react to user input.
The default for a QGraphicsTextItem is Qt::NoTextInteraction. This function also affects the ItemIsFocusable QGraphicsItem flag by setting it if flags is different from Qt::NoTextInteraction and clearing it otherwise.
By default, the text is read-only. To transform the item into an editor, set the Qt::TextEditable flag.
这样就比较清晰了,参数flags代表了QGraphicsTextItem的一些属性,
再来看看Qt::TextInteractionFlags
This enum specifies how a text displaying widget reacts to user input.
Constant Value Description
Qt::NoTextInteraction 0 No interaction with the text is possible.
Qt::TextSelectableByMouse 1 Text can be selected with the mouse and copied to the clipboard using a context menu or standard keyboard shortcuts.
Qt::TextSelectableByKeyboard 2 Text can be selected with

在QT图形视图框架下,子类化QGraphicsTextItem并设置交互标志后,发现只有小部分区域能捕获事件。问题在于QGraphicsTextItem未使用重写的boundingRect()。解决方案是不仅要设置painter的字体,还需设置QGraphicsTextItem的font和plainText,以确保正确计算事件区域。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



