Skip to main content
 首页 » 编程设计

python之基于内容的 TableView 单元格样式的 pyqt 样式表

2024年12月31日10xing901022

我找到了一种方法,可以根据单元格中的内容在 TableView 中进行基于 css 的单元格样式设置。以下代码显示了一个示例:

#!/usr/bin/python3 
 
from PyQt5 import QtWidgets, QtGui, QtCore 
 
class_values = ["zero", "one", "two"] 
 
class Cell(QtWidgets.QWidget): 
    def initFromItem(self, item): 
        self.setProperty('dataClass', class_values[int(item.text())]) 
 
class TDelegate(QtWidgets.QStyledItemDelegate): 
    def __init__(self, *a): 
        super(TDelegate, self).__init__(*a) 
        self.cell = Cell(self.parent()) 
 
    def paint(self, painter, option, index): 
        item = index.model().itemFromIndex(index) 
        self.cell.initFromItem(item) 
        self.initStyleOption(option, index) 
        style = option.widget.style() if option.widget else QtWidgets.QApplication.style() 
        style.unpolish(self.cell) 
        style.polish(self.cell) 
        style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, option, painter, self.cell) 
 
class TTableModel(QtGui.QStandardItemModel): 
    def __init__(self, parent=None): 
        super(TTableModel, self).__init__(parent) 
        for i in range(5): 
            self.appendRow([QtGui.QStandardItem(str((x+i) % 3)) for x in range(5)]) 
 
class TTableView(QtWidgets.QTableView): 
    def __init__(self, parent=None): 
        super(TTableView, self).__init__(parent) 
        self.setItemDelegate(TDelegate(self)) 
 
class Main(QtWidgets.QMainWindow): 
    def __init__(self): 
        super(Main, self).__init__() 
        self.table = TTableView(self) 
        self.model = TTableModel(self) 
        self.table.setModel(self.model) 
        self.setCentralWidget(self.table) 
 
if __name__ == "__main__": 
    import sys 
 
    app = QtWidgets.QApplication(sys.argv) 
    app.setStyleSheet(""" 
Cell[dataClass=zero]::item { background-color: gray; } 
Cell[dataClass=one]::item { background-color: green; font-style: italic } 
Cell[dataClass=two]::item { font-weight: bold } 
""") 
    mainWin = Main() 
    mainWin.show() 
    sys.exit(app.exec_()) 

这会生成一个这样的表:

具有每个单元格样式的 TableView

问题是虽然颜色有效,但字体样式无效。我究竟做错了什么?我怎样才能改进我的代码?它是如何工作的?例如,为什么 CSS 选择器必须包含 ::item。感激地收到所有答复。但请记住,基于 CSS 的样式对项目至关重要。

请您参考如下方法:

这是由于 qt (v5.9.5) 中的一个错误,它在创建 CE_ItemViewItem 时忽略了所有字体样式信息(参见 QStyleSheetStyle::drawControl)。通过创建诸如 CE_ToolBoxTabLabel 之类的其他东西(在 drawControl 中正确处理字体)来作弊确实会让你格式化字体,但会让你获得颜色,因为渲染使用按钮面调色板,而不是选项(或关联的 CSS)中指定的调色板。所以你可以拥有其中之一,但不能同时拥有两者。我知道没有解决方法。

至于这是如何工作的。在 QStyleSheetStyle::drawControl 中,对于 CE_ItemViewItem,查找 ::item 子角色的 CSS,如果存在,则应用于选项(但不是字体样式),然后根据更新的选项及其更新的调色板绘制项目。不幸的是,无法破解这段代码,因为无法从 PyQt 应用样式表(因为 QStyleSheet 不是 Qt 公共(public) API 的一部分)。