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

后端 未结 1 431
执笔经年
执笔经年 2021-01-14 17:13

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 fi

相关标签:
1条回答
  • 2021-01-14 17:58

    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_()
    
    0 讨论(0)
提交回复
热议问题