基于SQLite数据库,根据PyQt5表格单元格值设置行背景色
解决PyQt5表格根据SQLite中Yes/No列值设置行背景色的问题
要实现当SQLite的Curing表中Yes/No列值为1时,将PyQt5的QTableWidget对应行背景设为绿色,只需在现有代码的行遍历逻辑中添加背景色判断和设置即可,具体修改如下:
完整修改后的代码
from PyQt5.QtGui import QColor # 确保导入QColor def check_table(self): try: cur = self.con.cursor() cur.execute("SELECT * FROM Curing ORDER BY Time DESC LIMIT 100") result = cur.fetchall() col = [i[0] for i in cur.description] if result: self.tb_ch_table.setRowCount(len(result)) self.tb_ch_table.setColumnCount(len(col)) self.tb_ch_table.setHorizontalHeaderLabels(col) # 定位Yes/No列的索引(替换成你实际的列名) yes_no_col_name = "Yes/No" yes_no_col_idx = col.index(yes_no_col_name) for row, item in enumerate(result): # 填充单元格内容 for column, data in enumerate(item): table_item = QTableWidgetItem(str(data)) self.tb_ch_table.setItem(row, column, table_item) # 判断当前行Yes/No列值是否为1,是则设置行背景色为绿色 if item[yes_no_col_idx] == 1: for col_idx in range(len(col)): cell_item = self.tb_ch_table.item(row, col_idx) if cell_item: # 可根据需求调整颜色,这里用半透明绿色 cell_item.setBackground(QColor(0, 255, 0, 100)) else: return QTimer.singleShot(5000, self.check_table) except Exception as e: self.frame_ch.setStyleSheet("background-color:rgb(255, 0, 0);") self.show_ch_msg(msg=str(e))
关键修改说明
- 定位目标列:通过
col.index(yes_no_col_name)获取Yes/No列的索引,确保能准确判断每行的目标值(注意替换成你表中实际的列名)。 - 设置行背景色:在填充完当前行所有单元格内容后,判断目标列值是否为1,若是则遍历该行所有单元格,调用
setBackground设置背景色。 - 颜色选择:示例中使用半透明绿色(
QColor(0,255,0,100)),你也可以直接用QColor("green")设置纯绿色。
内容的提问来源于stack exchange,提问作者user9471162
相关产品推荐
相关产品推荐

