如何在PySide6的QLabel上设置标准Pixmap?
QLabel设置标准Pixmap失败的问题及解决
问题场景
尝试为QLabel设置标准Pixmap时出现两种错误:
错误1:传入类型不匹配
代码:
self.konfiguracja_groupBox.findChildren(qtw.QLabel, "polaczenie_label")[0].setPixmap(self.style().standardIcon(qtw.QStyle.SP_MessageBoxCritical))
报错信息:
TypeError: 'PySide6.QtWidgets.QLabel.setPixmap' called with wrong argument types:
PySide6.QtWidgets.QLabel.setPixmap(QIcon)
Supported signatures:
PySide6.QtWidgets.QLabel.setPixmap(Union[PySide6.QtGui.QPixmap, PySide6.QtGui.QImage])
错误2:方法调用方式错误
代码:
self.konfiguracja_groupBox.findChildren(qtw.QLabel, "polaczenie_label")[0].setPixmap(qtw.QStyle.standardPixmap(qtw.QStyle.SP_MessageBoxWarning))
报错信息:
TypeError: descriptor 'standardPixmap' for 'PySide6.QtWidgets.QStyle' objects doesn't apply to a 'StandardPixmap' object
解决方法
处理类型不匹配问题
standardIcon()返回的是QIcon对象,而setPixmap()要求传入QPixmap或QImage类型,需将QIcon转换为QPixmap:
label = self.konfiguracja_groupBox.findChildren(qtw.QLabel, "polaczenie_label")[0] icon = self.style().standardIcon(qtw.QStyle.SP_MessageBoxCritical) # 可自定义图标尺寸,示例为24x24 label.setPixmap(icon.pixmap(qtw.QSize(24, 24)))
修正方法调用方式
standardPixmap()是实例方法,必须通过当前控件的style实例调用,不能直接用QStyle类调用:
label = self.konfiguracja_groupBox.findChildren(qtw.QLabel, "polaczenie_label")[0] pixmap = self.style().standardPixmap(qtw.QStyle.SP_MessageBoxWarning) label.setPixmap(pixmap)
简化写法(推荐)
直接合并为一行,确保参数类型和调用方式正确:
self.konfiguracja_groupBox.findChildren(qtw.QLabel, "polaczenie_label")[0].setPixmap( self.style().standardPixmap(qtw.QStyle.SP_MessageBoxCritical) )
内容的提问来源于stack exchange,提问作者Radar32
相关产品推荐
相关产品推荐

