python - 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_()
解决方案
您需要对表进行子类化,覆盖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()
推荐阅读
- python - 在python中请求超时
- typescript - Typescript 中的递归类型映射
- sql - VBA SQL Access 数据库查询日期语句
- c++ - Qgraphics项目变慢
- delphi - 设计了一个电子邮件系统。给出一个不熟悉的异常
- snowflake-cloud-data-platform - 在 Snowflake SQL 中解析 JSON 数组键/值
- android - 查看某个 Fragment 时隐藏 AppBarLayout
- python - 如何更改 pygame 窗口顶部栏的颜色?
- node.js - Nodemon -e 不使用给定的扩展触发
- python - KivyMD 如何更改 MDToolbar 标题大小和字体?