首页 > 解决方案 > 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_())

标签: pythonpyqt5pyside2qtablewidget

解决方案


如果该列与您要隐藏的列匹配,则最简单的解决方案是覆盖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 不会传播给它们的子级.


推荐阅读