如何更改QTableView的单元格背景颜色

时间:2019-06-12 17:15:08

标签: python pyqt5 qtableview qabstracttablemodel

我有一个显示QAbstractTableModel的表格视图,我设法为数据函数中的一行着色,但是我只想为单元格着色而不是整个行。即如果单元格值=“错误”,我想将其涂成红色

我尝试使用setData函数为单元格设置颜色

std::stringstream ss(inp);

1 个答案:

答案 0 :(得分:0)

尝试一下:

import sys
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *


class Model(QAbstractTableModel):
    def __init__(self, parent=None):
        super(Model, self).__init__(parent)
        self._data = [[['%d - %d' % (i, j), False] for j in range(10)] for i in range(10)]

    def rowCount(self, parent):
        return len(self._data)

    def columnCount(self, parent):
        return len(self._data[0])

    def flags(self, index):
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable

    def data(self, index, role):
        if index.isValid():
            data, changed = self._data[index.row()][index.column()]

            if role in [Qt.DisplayRole, Qt.EditRole]:
                return data

            if role == Qt.BackgroundRole and data == "In error":        # <---------
                return QBrush(Qt.red) 

    def setData(self, index, value, role):
        if role == Qt.EditRole:
            self._data[index.row()][index.column()] = [value, True]
            self.dataChanged.emit(index, index)
            return True
        return False

if __name__ == '__main__':
    app = QApplication(sys.argv)

    tableView = QTableView()
    m = Model(tableView)
    tableView.setModel(m)
    tableView.show()

    sys.exit(app.exec_())

enter image description here