首页 > 解决方案 > how to create QTableview cell hover function

问题描述

I created a table with QTableview. I tried to add mouse hover function (if I keep mouse on particular cell) to change cursor style. I couldn't able to fine any inbuilt function mouse hover connect function in QTableview. so i used mouse table.entered.connect(on_entered) for changing cursor. leave function not available. so I am facing below issue showed in picture. hand cursor change in cell(1,1) but not changing back to arrow when leave cell(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_()

enter image description here

enter image description here

enter image description here

enter image description here

标签: pythonpyqt5hoverqtableview

解决方案


您需要对表进行子类化,覆盖mouseMoveEvent并检查鼠标位置处的索引,使用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()

推荐阅读