我有一个QTableWidget,其中的某些QTableWidgetItem包含单个QIcon(不是按钮,不是可单击的,只是图像)。有人可以建议我如何将图标居中吗? 我在下面提供了一些示例代码,这些示例代码可以正确显示图标,但是无法居中(setTextAlignment似乎适用于包含文本但显然不适用于图标的项目)。
status_item = QtGui.QTableWidgetItem()
status_icon = QtGui.QIcon()
status_icon.addPixmap(QtGui.QPixmap(icon_file), QtGui.QIcon.Normal, QtGui.QIcon.Off)
status_item.setIcon(status_icon)
self.ServiceTableWidget.setItem(row, 0, status_item)
self.ServiceTableWidget.item(row, 0).setTextAlignment(QtCore.Qt.AlignHCenter) #not working
我也尝试使用QIcon.paint()方法,尽管我可能执行不正确,但该方法不起作用:
status_icon.paint(QtGui.QPainter(), QtCore.QRect(), QtCore.Qt.AlignCenter)
谢谢!
答案 0 :(得分:0)
您可以使用委托:
from PyQt5 import QtCore, QtGui, QtWidgets
class IconDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(IconDelegate, self).initStyleOption(option, index)
if option.features & QtWidgets.QStyleOptionViewItem.HasDecoration:
s = option.decorationSize
s.setWidth(option.rect.width())
option.decorationSize = s
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.ServiceTableWidget = QtWidgets.QTableWidget(3, 3)
delegate = IconDelegate(self.ServiceTableWidget) # <---
self.ServiceTableWidget.setItemDelegate(delegate) # <---
icon_file = "lamp.png"
status_item = QtWidgets.QTableWidgetItem()
status_icon = QtGui.QIcon()
status_icon.addPixmap(QtGui.QPixmap(icon_file), QtGui.QIcon.Normal, QtGui.QIcon.Off)
status_item.setIcon(status_icon)
self.ServiceTableWidget.setItem(0, 0, status_item)
self.setCentralWidget(self.ServiceTableWidget)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())