Search code examples
pythonpyqtpyqt5qcombobox

PyQt5 ComboBox - how do I set the color of CurrentText without affecting the dropdown list?


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_()


Solution

  • 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_()