我有一个QTableView,有三列第二列是关于数字,只有三种类型。我想为这三种 "类型 "的数字(1,-1,0)设置不同的颜色,用不同的颜色为它们的行着色。我如何才能做到这一点?
self.tableView = QTableView(self.tabSentimento)
self.tableView.setGeometry(QRect(550,10,510,700))
self.tableView.setObjectName(_fromUtf8("TabelaSentimento"))
self.tableView.setModel(self.model)
self.tableView.horizontalHeader().setStretchLastSection(True)
困扰。我用了 horizontalheader().setStrechLastSection(True)
因为我打开了一个现有的csv文件(使用一个按钮)到我的tableview中。
你必须在模型中定义颜色,而不是在视图中。
def data(self, index, role):
...
if role == Qt.BackgroundRole:
return QBrush(Qt.yellow)
编辑:这是一个工作的例子,除了颜色的部分 完全从偷来的。http:/www.saltycrane.comblog200706pyqt-42-qabstracttablemodelqtableview
from PyQt4.QtCore import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
my_array = [['00','01','02'],
['10','11','12'],
['20','21','22']]
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QTableView):
def __init__(self, *args):
QTableView.__init__(self, *args)
tablemodel = MyTableModel(my_array, self)
self.setModel(tablemodel)
class MyTableModel(QAbstractTableModel):
def __init__(self, datain, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arraydata = datain
def rowCount(self, parent):
return len(self.arraydata)
def columnCount(self, parent):
return len(self.arraydata[0])
def data(self, index, role):
if not index.isValid():
return QVariant()
# vvvv this is the magic part
elif role == Qt.BackgroundRole:
if index.row() % 2 == 0:
return QBrush(Qt.yellow)
else:
return QBrush(Qt.red)
# ^^^^ this is the magic part
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
if __name__ == "__main__":
main()