PyQt5表格单元格进度条背景透明及文本属性调整问题求助
问题原因分析
你设置的QTableWidgetItem样式没生效,核心原因是你给单元格添加了QProgressBar作为cellWidget后,这个进度条会完全覆盖单元格内的item——相当于进度条是单元格的顶层控件,item被压在下面根本看不到,所以你给item加的对齐、颜色、背景透明全都白搭。
解决方案
直接在QProgressBar上做所有样式设置,进度条本身支持显示文本,不需要额外的item。修改代码如下:
修改后的table_layout.py代码
from PyQt5.QtWidgets import QMainWindow, QTableWidget, QProgressBar from PyQt5.QtGui import QColor from PyQt5.QtCore import Qt class TableExample(QMainWindow): def __init__(self, data, column_colors): super().__init__() self.data = data self.column_colors = column_colors self.initUI() def initUI(self): self.setWindowTitle('Progress Bars') self.setGeometry(100, 100, 600, 400) rows = len(self.data) columns = len(self.data[0]) self.table = QTableWidget(self) self.setCentralWidget(self.table) self.table.setRowCount(rows) self.table.setColumnCount(columns) column_titles = ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX"] self.table.setHorizontalHeaderLabels(column_titles) for col in range(columns): color = self.column_colors[col] for row in range(rows): value = self.data[row][col] progress = QProgressBar() progress.setValue(value) # 让进度条显示百分比文本 progress.setFormat(f"{value}%") # 设置文本对齐:右对齐+垂直居中 progress.setAlignment(Qt.AlignRight | Qt.AlignVCenter) # 样式表:设置进度块颜色、文本颜色、进度条背景透明、去掉边框 style = f""" QProgressBar {{ background-color: transparent; border: none; color: blue; }} QProgressBar::chunk {{ background-color: {color.name()}; }} """ progress.setStyleSheet(style) # 直接把进度条设为cellWidget,不需要item了 self.table.setCellWidget(row, col, progress) self.show() def updateTable(self, new_data): rows = len(new_data) columns = len(new_data[0]) for col in range(columns): for row in range(rows): new_value = new_data[row][col] # 直接获取进度条更新值和文本 progress = self.table.cellWidget(row, col) progress.setValue(new_value) progress.setFormat(f"{new_value}%")
关键修改点说明
- 移除了所有
QTableWidgetItem相关代码,进度条直接承担显示文本的功能 - 用
progress.setFormat()设置进度条显示的百分比文本 - 用
progress.setAlignment()设置文本的对齐方式,和你原来给item设置的一致 - 通过样式表给进度条设置:
background-color: transparent:让进度条背景透明color: blue:设置文本颜色为蓝色border: none:去掉默认的进度条边框(如果需要边框可以删掉这行)
- 更新数据时,直接修改进度条的
value和format,不需要再操作item
这样修改后,你要的透明背景、文本右对齐+垂直居中、自定义文本颜色这些效果就都能正常显示了。
内容的提问来源于stack exchange,提问作者Kankan2000
相关产品推荐
相关产品推荐

