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

2023-12-09

以下代码片段正确设置了组合框下拉列表中各个条目的颜色。但是,当选择一个项目并将其传输到 CurrentText 字段时,all下拉列表中的条目的颜色更改为 CurrentText 的颜色。如何传输要显示为 CurrentText 的条目的颜色without影响下拉列表?

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

你必须使用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_()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PyQt5 ComboBox - 如何设置 CurrentText 的颜色而不影响下拉列表? 的相关文章

随机推荐