python - Disable the sort arrow in a specific column in QTableWidget with PyQt/PySide
问题描述
I would like to remove the arrow from the first column heading so the title is centered with the checkboxes. All of this without disabling the possibility to sort the column.
This is my current code.
import sys
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QApplication,
QProxyStyle,
QStyle,
QTableWidget,
QTableWidgetItem,
)
class ProxyStyle(QProxyStyle):
def subElementRect(self, e, opt, widget):
r = super().subElementRect(e, opt, widget)
if e == QStyle.SE_ItemViewItemCheckIndicator:
r.moveCenter(opt.rect.center())
return r
class Table(QTableWidget):
def __init__(self):
QTableWidget.__init__(self, 3, 1)
self._style = ProxyStyle(self.style())
self.setStyle(self._style)
for i in range(self.rowCount()):
for j in range(self.columnCount()):
it = QTableWidgetItem()
self.setItem(i, j, it)
it.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
it.setCheckState(Qt.Checked if (i + j) % 2 == 0 else Qt.Unchecked)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Table()
w.show()
sys.exit(app.exec_())
解决方案
如果该列与您要隐藏的列匹配,则最简单的解决方案是覆盖QStyleOptionHeaderdrawControl()
并将其设置为 0。indicator
class ProxyStyle(QProxyStyle):
# ...
def drawControl(self, ctl, opt, qp, widget=None):
if ctl == QStyle.CE_HeaderSection and opt.orientation == Qt.Horizontal:
if opt.section == widget.parent().property('hideSortIndicatorColumn'):
opt.sortIndicator = 0
super().drawControl(ctl, opt, qp, widget)
class Table(QTableWidget):
def __init__(self):
# ...
self.setProperty('hideSortIndicatorColumn', 0)
请注意,在小部件上设置样式并不总是足以用于具有子级的复杂小部件。
在您的情况下,它可以工作,因为您将当前样式添加到代理构造函数,但这意味着样式的所有权将完全由代理获取,并且任何其他 QWidget 从那一刻起将使用代理(这几乎是与将代理设置为整个应用程序相同)。
另一种方法是创建不带任何参数的代理(在这种情况下,将使用默认原生样式的新实例),但这也意味着小部件的任何子级都不会继承该样式,因为 QStyles 不会传播给它们的子级.
推荐阅读
- android - 具有自定义笔划的 MaterialButton
- javascript - 如何在本机反应中将 userId 传递给哨兵?
- react-native - TypeError:未定义不是对象(评估'loginState.isLoading')
- mongodb - 从结果中排除空值
- flutter - Flutter Divider 是错误的颜色
- android - 需要来自 Android ContentResolver 的路径
- visual-studio - Visual Studio 使用多个不同的程序集、产品和文件名编译同一个项目
- node.js - 将十六进制数据保存到 NodeJS 中的文件
- python-3.x - python 3.x insert 函数在使用负一进行索引时的行为与其他列表函数不同,这是有原因的吗?
- php - 如何确定给定的邮政编码是否介于 (K2T - K4P) 之间