如何创建QTableview单元格悬停功能

how to create QTableview cell hover function

我用 QTableview 创建了一个 table。我尝试添加鼠标悬停功能(如果我将鼠标放在特定单元格上)以更改光标样式。我无法在 QTableview 中完善任何内置功能的鼠标悬停连接功能。所以我用鼠标 table.entered.connect(on_entered) 来改变光标。离开功能不可用。所以我面临下面图片中显示的问题。手形光标在单元格 (1,1) 中发生变化,但离开单元格 (1,1)

时不会变回箭头
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

data=[[1,1],[1,2],['a','b']]

class TableModel(QAbstractTableModel):
    def __init__(self, data,header_labels=None):
        super().__init__();self._data = data;self.header_labels=header_labels

    def data(self, index, role):
        if role == Qt.DisplayRole:return self._data[index.row()][index.column()]
    def rowCount(self, index):return len(self._data)
    def columnCount(self, index):return len(self._data[0])
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if self.header_labels==None:self.header_labels=range(len(self._data[0]))
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:return self.header_labels[section]
        return QAbstractTableModel.headerData(self, section, orientation, role)

def on_entered(index):
    if index.row()==1 and index.column()==1: table.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
    else:table.setCursor(QCursor(Qt.CursorShape.ArrowCursor))
app = QApplication(sys.argv)
window = QWidget()
vl=QVBoxLayout(window)

searchbar = QLineEdit()
table=QTableView()
proxy_model = QSortFilterProxyModel()
model = TableModel(data)
proxy_model.setSourceModel(model)
table.setModel(proxy_model)

table.entered.connect(on_entered)
table.setMouseTracking(True)
table.setSelectionMode(QAbstractItemView.NoSelection)
table.setFocusPolicy(Qt.FocusPolicy.NoFocus)

vl.addWidget(table)
t=TableModel(data[1:],data[0])
proxy_model.setSourceModel(t)
window.show()
app.exec_()

您需要继承 table,覆盖 mouseMoveEvent and check the index at the mouse position using indexAt

由于在鼠标移动过程中可能会发生鼠标交互,因此您应该仅在 没有 按钮被按下时设置光标。 mouseTracking 属性 仍然是必需的。

class CursorShapeTable(QTableView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setMouseTracking(True)

    def mouseMoveEvent(self, event):
        super().mouseMoveEvent(event)
        if not event.buttons():
            index = self.indexAt(event.pos())
            if index.row() == 1 and index.column() == 1:
                self.setCursor(Qt.CursorShape.PointingHandCursor)
            else:
                self.unsetCursor()