使用 QTableView class 时如何检测鼠标光标离开视口?
how can I detect the mouse cursor leaves the viewport when using QTableView class?
我找到了 QAbstractItemView class 的 'viewportEntered' 信号,它是 QTableView class 的超级 class。如果我使用这个信号来做一个动作,我还需要一种方法来在鼠标光标离开视口时撤消这个动作。
需要跟踪指示的要求在什么时候满足,然后发出新信号:
from PyQt5 import QtCore, QtGui, QtWidgets
class TableView(QtWidgets.QTableView):
viewportLeaved = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super(TableView, self).__init__(*args, **kwargs)
self.is_entered = False
self.setMouseTracking(True)
self.viewportEntered.connect(self.on_viewportEntered)
def on_viewportEntered(self):
self.is_entered = True
def viewportEvent(self, event):
res = super(TableView, self).viewportEvent(event)
if event.type() == QtCore.QEvent.Leave:
if self.is_entered:
self.viewportLeaved.emit()
self.is_entered = False
return res
def mouseMoveEvent(self, event):
super(TableView, self).mouseMoveEvent(event)
if self.indexAt(event.pos()).isValid() and self.is_entered:
self.viewportLeaved.emit()
self.is_entered = False
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = TableView()
w.resize(640, 480)
model = QtGui.QStandardItemModel(4, 5)
w.setModel(model)
w.viewportEntered.connect(lambda: print("viewportEntered", QtCore.QDateTime.currentDateTime().toString()))
w.viewportLeaved.connect(lambda: print("viewportLeaved", QtCore.QDateTime.currentDateTime().toString()))
w.show()
sys.exit(app.exec_())
我找到了 QAbstractItemView class 的 'viewportEntered' 信号,它是 QTableView class 的超级 class。如果我使用这个信号来做一个动作,我还需要一种方法来在鼠标光标离开视口时撤消这个动作。
需要跟踪指示的要求在什么时候满足,然后发出新信号:
from PyQt5 import QtCore, QtGui, QtWidgets
class TableView(QtWidgets.QTableView):
viewportLeaved = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super(TableView, self).__init__(*args, **kwargs)
self.is_entered = False
self.setMouseTracking(True)
self.viewportEntered.connect(self.on_viewportEntered)
def on_viewportEntered(self):
self.is_entered = True
def viewportEvent(self, event):
res = super(TableView, self).viewportEvent(event)
if event.type() == QtCore.QEvent.Leave:
if self.is_entered:
self.viewportLeaved.emit()
self.is_entered = False
return res
def mouseMoveEvent(self, event):
super(TableView, self).mouseMoveEvent(event)
if self.indexAt(event.pos()).isValid() and self.is_entered:
self.viewportLeaved.emit()
self.is_entered = False
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = TableView()
w.resize(640, 480)
model = QtGui.QStandardItemModel(4, 5)
w.setModel(model)
w.viewportEntered.connect(lambda: print("viewportEntered", QtCore.QDateTime.currentDateTime().toString()))
w.viewportLeaved.connect(lambda: print("viewportLeaved", QtCore.QDateTime.currentDateTime().toString()))
w.show()
sys.exit(app.exec_())