PySide6/PyQT自定义QComboBox实现单元格不同颜色
class ColorDelegate(QStyledItemDelegate):
def __init__(self, colors, parent=None):
super().__init__(parent)
self.colors = colors
def paint(self, painter, option, index):
if index.row() < len(self.colors):
color = self.colors[index.row()]
painter.fillRect(option.rect, color)
super().paint(painter, option, index)
class CustomComboBox(QComboBox):
def __init__(self, items, colors, parent=None):
super().__init__(parent)
self.addItems(items)
self.setItemDelegate(ColorDelegate(colors, self))
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.comboBox = CustomComboBox(
items=["Item 1", "Item 2", "Item 3"],
colors=[QColor(255, 255, 255), QColor(0, 236, 241), QColor(254, 32, 2)],
)
layout = QVBoxLayout(self)
layout.addWidget(self.comboBox)
self.setLayout(layout)
self.comboBox.show()
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()