0

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Avo Asatryan
  • 404
  • 8
  • 21
  • 1
    See https://stackoverflow.com/questions/50711763/pyqt5-combobox-how-do-i-set-the-color-of-currenttext-without-affecting-the-dro – S. Nick Jun 10 '18 at 13:51
  • there is described how to change font color, i am asking an other thing. however, thank u for attention – Avo Asatryan Jun 10 '18 at 14:42

1 Answers1

2

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241