使用QTableView类时,如何检测鼠标光标离开视口?

时间:2019-03-04 02:05:59

标签: python pyqt qtableview

我发现了QAbstractItemView类的'viewportEntered'信号,它是QTableView类的超类。如果使用此信号执行操作,则还需要一种在鼠标光标离开视口时撤消该操作的方法。

1 个答案:

答案 0 :(得分:1)

有必要跟踪何时满足指示的要求,然后发出新信号:

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_())