【问题标题】:PyQt5 ComboBox - how do I set the color of CurrentText without affecting the dropdown list?PyQt5 ComboBox - 如何在不影响下拉列表的情况下设置 CurrentText 的颜色?
【发布时间】:2018-11-15 15:06:39
【问题描述】:

以下 sn-p 正确设置了 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_()

【问题讨论】:

  • 当我单击组合框中的一个项目时,它不会为我执行此操作,其余项目颜色不会更改为当前选定项目的颜色。我在 Windows 8,python3.6.0,pyqt5.6.0
  • 我应该提到我使用的是 Linux、Python 3.6.5 和 PyQt5 5.10-3。此外,单击一个项目,关闭下拉菜单,然后重新打开它。那是所有颜色都变为单一颜色的时候。

标签: python pyqt pyqt5 qcombobox


【解决方案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_()

【讨论】:

  • 做到了 - 谢谢!我正在撕扯头发,寻找大海捞针!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
相关资源
最近更新 更多