Setting Pyqt4 TableWidget background Colour based on certain value loaded from Sqlite Database

寵の児 提交于 2019-12-02 10:46:00

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 
  • Using the 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))]
  • Using a delegate:

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:

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