python - PyQt5 ComboBox - 如何在不影响下拉列表的情况下设置 CurrentText 的颜色?
问题描述
以下代码片段正确设置了 ComboBox 下拉列表中各个条目的颜色。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. 如何在不影响下拉列表的情况下将条目的颜色转换为 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_()
解决方案
你必须使用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_()
推荐阅读
- apache-camel - 使用嵌套 EL 动态读取编号的标头值不再起作用
- laravel - laravel 该路由不支持 PUT 方法。支持的方法:GET、HEAD
- sql - 与 select 中的特定条件相加
- python - Matplotlib:显示列表中的特定图形
- android - If 语句,Android Studio 与 Firebase
- javascript - ReactJS - MongoDB - JavaScript:MongoDB 没有从 API 接收任何数据
- html - Chrome 80 中的网格模板列计算不一致
- python - 在 django oscar 的“篮子”中添加新元素
- postgresql - 当主节点或备用节点发生故障时,pgpool-II 与看门狗委托 IP 的会话终止
- r - 从 R 中有多个分隔符的列中分离出 6 个数值