如何在Python代码中调整QTableWidgetItem内的图标尺寸
解决QTableWidgetItem图标过小的问题
QTableWidgetItem本身确实没有setIconSize()方法,图标显示尺寸由表格控件的设置或单元格尺寸控制,给你三种可行的解决办法:
方法一:设置表格全局图标尺寸
直接给QTableWidget设置统一的图标大小,所有带图标的单元格都会遵循这个尺寸:
# 尺寸按需调整,在设置图标前后添加均可 schedule_grid.setIconSize(QSize(32, 32))
方法二:单独调整目标列宽与行高
如果不想全局修改,只针对最后一列(索引3)的图标调整,可以设置列宽和对应行的高度,让图标有足够空间显示:
# 设置第4列(索引3)的宽度 schedule_grid.setColumnWidth(3, 60) # 在循环内设置当前行的高度 schedule_grid.setRowHeight(row, 60)
方法三:自定义委托精细控制(进阶)
如果需要对图标尺寸做更灵活的定制,比如不同行用不同大小,可以自定义ItemDelegate:
from PyQt5.QtWidgets import QStyledItemDelegate from PyQt5.QtGui import QPainter from PyQt5.QtCore import Qt class IconDelegate(QStyledItemDelegate): def paint(self, painter, option, index): # 只处理第4列的图标 if index.column() == 3: icon = index.data(Qt.DecorationRole) if icon is not None: # 绘制指定大小的图标,尺寸按需调整 pixmap = icon.pixmap(QSize(40, 40)) painter.drawPixmap(option.rect.center() - pixmap.rect().center(), pixmap) return # 其他列用默认绘制逻辑 super().paint(painter, option, index) # 给表格的目标列设置委托 delegate = IconDelegate() schedule_grid.setItemDelegateForColumn(3, delegate)
另外注意你原代码里的语法错误:schedule_grid.setItem(row, 3 row_img)缺少逗号,应改为schedule_grid.setItem(row, 3, row_img)。
内容的提问来源于stack exchange,提问作者weave
相关产品推荐
相关产品推荐

