How to change cell's background color of a QTableView [duplicate]

流过昼夜 提交于 2019-12-20 03:51:28

问题


I have a table view displaying a QAbstractTableModel, I managed to color a row within the data function but I just want to color the cell and not the entire row. i.e if the cell value = "In error" I want to color it in red

I have tried to set a color to the cell using the setData function

class TicketGUI(QAbstractTableModel):
    def __init__(self, data):
        QAbstractTableModel.__init__(self)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parent=None):
        return self._data.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
            if role == Qt.TextAlignmentRole:
                return Qt.AlignCenter
            if role == Qt.BackgroundRole:
                if self._data.iloc[index.row(), 2] == "In error":
                    self.setData(self.index(index.row(), index.column()), QBrush(Qt.red), Qt.BackgroundRole) #do not work
                    #return QBrush(Qt.red) works but color the entire row

回答1:


Try it:

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_())



来源:https://stackoverflow.com/questions/56567353/how-to-change-cells-background-color-of-a-qtableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!