[英]how can I detect the mouse cursor leaves the viewport when using QTableView class?
I found the 'viewportEntered' signal of QAbstractItemView class which was the super class of the QTableView class.我发现QAbstractItemView类的“viewportEntered”信号,它是 QTableView 类的超类。 If I use this signal to do an action, I also need a way to undo this action when the mouse cursor leaves the viewport.如果我使用这个信号来做一个动作,我还需要一种方法来在鼠标光标离开视口时撤消这个动作。
It is necessary to tracking in what moment the requirement that is indicated is fulfilled and then to emit the new signal:有必要跟踪指示的要求在什么时刻得到满足,然后发出新信号:
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_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.