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 Tableview background color based on text value rather than True or False which works .
Problem is , In my setup I use TableWidget with a Button ( I used Qt Designer ) that loads the data from Sqlite database and I am not too sure how to implement below code into my setup as I dont entirely understand how it works:
def data(self, item, role):
if role == Qt.BackgroundRole:
if QSqlQueryModel.data(self, self.index(item.row(), 2), Qt.DisplayRole) == "Young":
return QBrush(Qt.yellow)
if role == Qt.DisplayRole:
if item.column() == 3:
return True if QSqlQueryModel.data(self, item, Qt.DisplayRole) == 1 else False
return QSqlQueryModel.data(self, item, role)
Below is my code for selecting and displaying Sqlite Data to TableWidget . I am using PyQT4 , Pyhton 2.7 .
self.load_btn.clicked.connect(self.loadData)
def loadData(self):
##DB Connection ###
cursor = conn.cursor()
query = "SELECT * FROM Tadata"
cursor.execute(query)
results = cursor.fetchall()
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,QtGui.QTableWidgetItem(str(data)))
Database used is sqlite . 4 rows and 4 columns .Column headers : Number , Company, Equipment , Status . 'Status' records comprises of 'YES' or 'NO' . So wherever 'NO' is , I wish for background to be red
My Table in database
tableview colour based on certain value