pyqt-在TableView中更改行〜单元格颜色 [英] pyqt - Change row~cell color in TableView
问题描述
我有一个包含三列的QTableView 第二列是数字,只有三种类型:1,-1和0. 我想为数字的这三个类型"(1,-1,0)使用不同的颜色,并用不同的颜色为其行着色.我该怎么办?
I have a QTableView with three columns The second column is about numbers, there are only three types: 1, -1 and 0. I want to have different colors for this three "types" of numbers (1,-1,0), coloring their rows with different colors. How can i do it?
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)
obs:之所以使用horizontalheader().setStrechLastSection(True)
,是因为我在表视图中打开了一个现有的csv文件(使用按钮).
obs: I used horizontalheader().setStrechLastSection(True)
because I opened an existing csv file (using a button) into my tableview.
推荐答案
您必须在模型中定义颜色,而不是在视图中定义颜色:
You have to define the color in the model, not in the view:
def data(self, index, role):
...
if role == Qt.BackgroundRole:
return QBrush(Qt.yellow)
这是一个工作示例,除了 http://www.saltycrane.com/blog/2007/06/pyqt-42-qabstracttablemodelqtableview/
Here's a working example, except for the color part completely stolen from http://www.saltycrane.com/blog/2007/06/pyqt-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()
这篇关于pyqt-在TableView中更改行〜单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!