如何更改QTableView的单元格背景颜色 [英] How to change cell's background color of a QTableView

查看:2502
本文介绍了如何更改QTableView的单元格背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

尝试一下:

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

这篇关于如何更改QTableView的单元格背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆