Backstory: Using an imported UI, I place my table onto a QTableView. I also make use of alternating row colors to better differentiate rows.
Problem: I'm looking to color the row of a table that contains a True value in one of the columns. I am able to color the cell, but have not found a way to color the entire row. I use a PandasModel class to format the tables:
class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row()][index.column()])
if role == QtCore.Qt.BackgroundRole:
row = index.row()
col = index.column()
if self._data.iloc[row,col] == True:
return QtGui.QColor('yellow')
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[col]
return None
I've look through numerous examples, and I am aware there may be multiple ways to color a table using QBrush or QColor, but so far the best I am able to do is simply color the cell that contains the True value. Splicing in code from other examples, I thought it was possible that the col = index.column() was getting in the way, as maybe it was limiting it to the cell, however, when I remove this it becomes ambiguous.
Important: I am wanting to keep the alternating row colors that I set elsewhere in the script, so please keep that in mind! I am only looking to color the specifics rows that contain any True value.
CodePudding user response:
If the column of the boolean values is known, you just have to check for the value of that column at the given row of the index.
Supposing that the column index is 2:
class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
self.boolColumn = 2
# ...
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row()][index.column()])
if role == QtCore.Qt.BackgroundRole:
row = index.row()
if self._data.iloc[row, self.boolColumn] == True:
return QtGui.QColor('yellow')
Note: return None is implicit at the end of a function block, you don't need to specify it.
