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

后端 未结 1 1851
误落风尘
误落风尘 2021-01-28 02:33

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

相关标签:
1条回答
  • 2021-01-28 02:40

    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:

    0 讨论(0)
提交回复
热议问题