我已经找到了一种方法,可以根据单元格中的内容在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的样式的需要是必不可少的项目。
发布于 2018-10-12 12:57:09
这是由于qt (v5.9.5)中的一个错误,该错误在创建CE_ItemViewItem
(请参阅QStyleSheetStyle::drawControl
)时忽略所有字体样式信息。通过创建像CE_ToolBoxTabLabel
(它可以正确处理drawControl
中的字体)这样的东西来欺骗你,确实会得到字体格式,但会让你得到颜色,因为渲染使用的是按钮表面调色板,而不是选项(或相关的CSS)中指定的调色板。所以你可以选择其中一个,但不能两个都有。我不知道有什么变通方法。
关于它是如何工作的。在CE_ItemViewItem
的QStyleSheetStyle::drawControl
中,查找::item
的子角色的CSS,并将其应用于选项的副本(但不应用于字体样式),然后根据更新的选项及其更新的调色板绘制项目。不幸的是,由于无法从PyQt应用样式表(因为QStyleSheet不是Qt的公共API的一部分),所以无法进入这段代码。
https://stackoverflow.com/questions/52759386
复制相似问题