基于SQLite数据设置PyQt4 TableWidget单元格背景色的实现疑问
Hey there! I see you're working with PyQt4 and Python 2.7, trying to highlight cells in your QTableWidget where the Status is "NO". Let's adapt your existing data loading code to handle this easily—no need to switch to a TableView delegate unless you want to, since we can modify the QTableWidgetItem directly as you create it.
Step-by-Step Modification
Your current code inserts each row's data into the table widget. We just need to add a check when setting the Status column (which is index 3, since columns are 0-indexed: Number=0, Company=1, Equipment=2, Status=3). When the value is "NO", we'll set the cell's background color to red.
Here's the updated loadData function with the added logic:
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): item = QtGui.QTableWidgetItem(str(data)) # Check if we're in the Status column (index 3) and value is "NO" if column_number == 3 and str(data).strip().upper() == "NO": # Set red background for this cell item.setBackgroundColor(QtGui.QColor("red")) # Optional: Make text white for better contrast item.setTextColor(QtGui.QColor("white")) self.tableWidget.setItem(row_number, column_number, item)
Key Details Explained
- We first create the
QTableWidgetItembefore checking its value—this lets us modify its properties before adding it to the table. - The check
str(data).strip().upper() == "NO"ensures we handle any accidental whitespace or case differences (like "no" or " NO ") in your database data. setBackgroundColor(QtGui.QColor("red"))is the PyQt4 method to set the cell's background color. You can also usesetBackground(QtGui.QBrush(QtGui.QColor("red")))if you prefer working with brushes, but both work for this use case.- The optional text color change makes the "NO" text more readable against the red background.
Alternative: Using a Delegate (For More Advanced Cases)
If you ever need more dynamic styling (like if your data updates after initial load), you could use a QItemDelegate subclass. But for your current setup where you're loading data once, modifying the item directly is simpler and fits your existing code flow perfectly.
Just drop this updated function into your code, and your Status column cells with "NO" should show up with a red background!
内容的提问来源于stack exchange,提问作者Garth

