在 PyQt5 中的 QComboBox 最前面添加图标
要在 PyQt5 中的 QComboBox 最前面增加图标,你需要使用自定义的 QComboBox 模型和代理。下面是一个实现此功能的示例代码:
from PyQt5.QtWidgets import QApplication, QComboBox, QStyledItemDelegate
from PyQt5.QtGui import QIcon, QPainter
from PyQt5.QtCore import Qt, QSize
class IconDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
if index.column() == 0:
# 获取图标和文本
icon = index.data(Qt.DecorationRole)
text = index.data(Qt.DisplayRole)
# 绘制图标和文本
painter.save()
painter.drawText(option.rect.adjusted(20, 0, 0, 0), Qt.AlignLeft|Qt.AlignVCenter, text)
painter.restore()
if icon is not None:
icon.paint(painter, option.rect.adjusted(0, 0, 20, 0), Qt.AlignmentFlag.AlignCenter, QIcon.Normal, QIcon.On)
else:
super().paint(painter, option, index)
class CustomComboBox(QComboBox):
def __init__(self, parent=None):
super().__init__(parent)
# 设置自定义的代理
self.setItemDelegate(IconDelegate())
def addItem(self, text, icon=None):
# 创建一个包含图标和文本的元组
itemData = (icon, text)
super().addItem(text, itemData)
def paintEvent(self, event):
painter = QPainter(self)
option = self.viewOptions()
self.style().drawComplexControl(QComboBox.ComplexControl.ComboLineEdit, option, painter, self)
super().paintEvent(event)
# 创建应用程序和主窗口
app = QApplication([])
window = CustomComboBox()
# 添加带有图标的选项
icon = QIcon('icon.png')
window.addItem('Option 1', icon)
# 显示窗口
window.show()
app.exec()
在这个示例中,我们创建了一个自定义的 QComboBox 子类 CustomComboBox,并使用自定义的代理 IconDelegate 来绘制图标和文本。在 addItem 方法中,我们将图标和文本一起存储在元组 itemData 中,并在调用 addItem 方法时传递给父类的 addItem 方法。
在 paintEvent 方法中,我们使用自定义的绘制方法绘制 QComboBox 的文本框部分,然后调用父类的 paintEvent 方法绘制下拉框部分。
注意:在这个示例中,我们使用了一个名为 'icon.png' 的图标文件,你需要将其替换为你自己的图标文件。
原文地址: https://www.cveoy.top/t/topic/pTJK 著作权归作者所有。请勿转载和采集!