0

我发现当我将 QGraphicsTextItem 添加到 Scene 时,MouseMoveEvent 会在没有按下鼠标按钮的情况下触发。我检查了 QgraphicsView.hasMouseTracking() 值,默认为 False。

仅当我将“TextItem”添加到场景时才会发生,而当我添加其他项目(RectItem、LineItem 等)时不会发生。为什么“TextItem”只会触发此问题?我使用了 Spyder4,我的测试代码是这样的。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPainter, QColor, QFont, QPen, QBrush, QPainterPath
from PyQt5.QtCore import Qt , QPointF
from PyQt5.QtWidgets import QGraphicsItem
import sys
global ui
class MyScene(QtWidgets.QGraphicsScene):
    c=0
    def mouseMoveEvent(self,e):
        super().mouseMoveEvent(e)
        print(ui.graphicsView.hasMouseTracking())
        print('move event! ',self.c)
        self.c+=1

    def mouseReleaseEvent(self, e):        
        super().mouseReleaseEvent(e)
        end=e.scenePos()
        text=QtWidgets.QGraphicsTextItem('haha')
        text.setPos(end.x(), end.y())
        self.addItem(text)    
        self.update()

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setObjectName("MainWindow")
        self.resize(800, 619)
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)      
        self.verticalLayout.addWidget(self.graphicsView)
        self.setCentralWidget(self.centralwidget) 
        self.scene = MyScene()
        self.graphicsView.setScene(self.scene)

app = QtWidgets.QApplication(sys.argv)
ui = MyWindow()
ui.show()
sys.exit(app.exec_())
4

0 回答 0