我有一个QTableView
并想要设置其项目边距的样式,并根据其模型值为其提供不同的颜色。但是,只要我设置样式表,它就会忽略Qt.BackgroundRole
等角色的数据。我的问题是:如何设置动态背景着色的边距。这是我的妈妈:
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import QTableView, QApplication
from PyQt5.QtCore import QAbstractTableModel, Qt, QTimer
from PyQt5.QtGui import QBrush
class Model(QAbstractTableModel):
counter = 0
COLORS = [QBrush(Qt.green), QBrush(Qt.red), QBrush(Qt.blue), QBrush(Qt.cyan)]
def rowCount(self, *_):
return 2
def columnCount(self, *_):
return 2
def data(self, index, role):
if role == Qt.DisplayRole:
return f'{index.row()} - {index.column()} - {self.counter}'
elif role == Qt.BackgroundRole:
ind = (index.row() + index.column() * 2 + self.counter) % 4
return self.COLORS[ind]
def change(self):
self.counter += 1
self.dataChanged.emit(self.index(0, 0), self.index(2, 2))
# Setup
app = QApplication(sys.argv)
model = Model()
view = QTableView()
view.setModel(model)
view.show()
# This is the line that causes the headache, I want to define some margins,
# however once setting this stylesheet it ignores my data calls with
# role == Qt.BackgroundRole
if True:
app.setStyleSheet('''
QTableView::item {
background-color: grey;
margin-top: 5px;
margin-bottom: 5px;
min-height: 20px;
}''')
# The timer simulates new data comming in. We want to color each cell according
# to the status of its value.
timer = QTimer()
timer.timeout.connect(model.change)
timer.start(500)
app.lastWindowClosed.connect(timer.stop)
sys.exit(app.exec_())
设置样式表时
不设置样式表时