Avo Asatryan
Avo Asatryan

Reputation: 414

colors in QComboBox items in place of QIcons

I'm using pyqt and wanted to display different colors with each item of a combobox.

we can do it for images:

combo.addItem(QIcon("path/to/image.png"), "Item 1")

but how to do it for colors?

Upvotes: 0

Views: 373

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

The solution is to create an icon using the QColor as a base, as shown below.

import sys

from PyQt5.QtWidgets import QApplication, QComboBox
from PyQt5.QtGui import QColor, QIcon, QPixmap


def get_icon_from_color(color):
    pixmap = QPixmap(100, 100)
    pixmap.fill(color)
    return QIcon(pixmap)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QComboBox()
    for text, color in (("item1", QColor("red")), ("item2", QColor(0xff00ff)), ("item3", QColor(0, 255, 0))):
        w.addItem(get_icon_from_color(color), text)
    w.show()
    sys.exit(app.exec_())

Upvotes: 3

Related Questions