Python 设置样式表时,QTableView会忽略数据
我有一个Python 设置样式表时,QTableView会忽略数据,python,python-3.x,pyqt,pyqt5,qtableview,Python,Python 3.x,Pyqt,Pyqt5,Qtableview,我有一个QTableView,我想设计它的项目边距,并根据它的型号值给它不同的颜色。但是,一旦我设置了样式表,它就会忽略角色的数据,如Qt.BackgroundRole。我的问题是:如何设置动态背景着色的边距。这是我的mwe: #!/usr/bin/env python3 import sys from PyQt5.QtWidgets import QTableView, QApplication from PyQt5.QtCore import QAbstractTableModel, Q
QTableView
,我想设计它的项目边距,并根据它的型号值给它不同的颜色。但是,一旦我设置了样式表,它就会忽略角色的数据,如Qt.BackgroundRole
。我的问题是:如何设置动态背景着色的边距。这是我的mwe:
#!/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_())
设置样式表时
不设置样式表时