I am trying to set background color of TableWidget based on certain value from data loaded from Sqlite database like in example below . I have seen below answer in PyQt Tablev
The solution of the post that samples is only valid if you use QTableView
, QTableWidget
does not allow to establish a new model, there are several options to solve this problem.
For the example I will assume that the data has the following form:
Number Company Equipment Status
---------- ---------- ---------- ----------
1 company1 Equipment1 YES
2 company2 Equipment2 NO
3 company3 Equipmen3 NO
4 company4 Equipment4 YES
setBackground()
method of QTableWidgetItem
self.tableWidget.setRowCount(0)
for row_number, row_data in enumerate(results):
self.tableWidget.insertRow(row_number)
for column_number, data in enumerate (row_data):
self.tableWidget.setItem(row_number,column_number, QTableWidgetItem(str(data)))
if column_number == 3 and data == "NO":
[self.tableWidget.item(row_number, c).setBackground(Qt.red) for c in range(len(row_data))]
class Delegate(QStyledItemDelegate):
def paint(self, painter, option, index):
ix = index.model().index(index.row(), 3)
if ix.data() == "NO":
painter.fillRect(option.rect,Qt.red)
QStyledItemDelegate.paint(self, painter, option, index)
[...]
self.tableWidget.setItemDelegate(Delegate(self.tableWidget))
Output: