3

The following snippet correctly sets the colors of individual entries in the ComboBox dropdown list. However, when an item is selected and transferred to the CurrentText field, all of the entries in the dropdown change to the color of CurrentText. How do I transfer the color of an entry to be displayed as CurrentText without affecting the dropdown list?

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ComboDemo(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        def combo_changed():
            for color in ('red', 'green', 'blue'):
                if color == cb.currentText():
                    cb.setStyleSheet('color: {}'.format(color))

        grid = QGridLayout()
        cb = QComboBox()
        grid.addWidget(cb, 0, 0)
        model = cb.model()
        for color in ('red', 'green', 'blue'):
            entry = QStandardItem(color)
            entry.setForeground(QColor(color))
            model.appendRow(entry)

        cb.currentIndexChanged.connect(combo_changed)

        self.setLayout(grid)
        self.show()

app = QApplication(sys.argv)
c = ComboDemo()
app.exec_()

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
OregonJim
  • 326
  • 2
  • 10
  • It doesn't do that for me when i click on a item in the combo box rest of the items color won't change to the current selected item's color. I am on Windows 8, python3.6.0, pyqt5.6.0 – U13-Forward Jun 06 '18 at 03:27
  • I should have mentioned that I'm on Linux, Python 3.6.5 and PyQt5 5.10-3. Also, click on an item, close the dropdown, and re-open it. That's when all the colors change to a single color. – OregonJim Jun 06 '18 at 03:31

1 Answers1

2

You have to use QComboBox:editable:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ComboDemo(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        def combo_changed():
            for color in ('red', 'green', 'blue'):
                if color == cb.currentText():
                    cb.setStyleSheet("QComboBox:editable{{ color: {} }}".format(color))

        grid = QGridLayout()
        cb = QComboBox()
        grid.addWidget(cb, 0, 0)
        model = cb.model()
        for color in ('red', 'green', 'blue'):
            entry = QStandardItem(color)
            entry.setForeground(QColor(color))
            model.appendRow(entry)

        cb.currentIndexChanged.connect(combo_changed)
        self.setLayout(grid)
        self.show()

app = QApplication(sys.argv)
c = ComboDemo()
app.exec_()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241