PyQt5 ComboBox - 如何在不影响下拉列表的情况下设置CurrentText的颜色?

时间:2018-06-06 03:16:35

标签: python pyqt pyqt5 qcombobox

以下代码段正确设置了ComboBox下拉列表中各个条目的颜色。但是,当选择一个项目并将其传送到CurrentText字段时,下拉列表中所有条目将更改为CurrentText的颜色。如何传输要显示为CurrentText 而不会影响下拉列表的条目的颜色?

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

1 个答案:

答案 0 :(得分:1)

您必须使用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_()