本文介绍了PyQt5 ComboBox - 如何在不影响下拉列表的情况下设置 CurrentText 的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码段正确设置了 ComboBox 下拉列表中各个条目的颜色.但是,当一个项目被选中并转移到 CurrentText 字段时,下拉列表中的所有条目将更改为 CurrentText 的颜色.如何转移条目的颜色以显示为 CurrentText 不影响下拉列表?
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_()
推荐答案
你必须使用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_()
这篇关于PyQt5 ComboBox - 如何在不影响下拉列表的情况下设置 CurrentText 的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!