PyQt5 – 为不可编辑的OFF状态的组合框设置按压时的背景颜色

  • Post category:Python

首先,需要使用PyQt5中的QComboBox类来创建一个组合框,例如:

from PyQt5.QtWidgets import QApplication, QWidget, QComboBox

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

        combo_box = QComboBox(self)
        combo_box.addItem("Option 1")
        combo_box.addItem("Option 2")
        combo_box.addItem("Option 3")

为了设置组合框按压时的背景颜色,需要定义一个子类继承QComboBox,并重写paintEvent方法。在该方法中,我们可以绘制自定义的背景颜色。

from PyQt5.QtGui import QColor, QPalette
from PyQt5.QtWidgets import QComboBox

class CustomComboBox(QComboBox):
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        if self.lineEdit().isEnabled():
            painter.fillRect(self.rect(), QColor(255, 255, 255))
        else:
            painter.fillRect(self.rect(), QColor(220, 220, 220))

        option = QStyleOptionComboBox()
        self.initStyleOption(option)
        self.style().drawComplexControl(QStyle.CC_ComboBox, option, painter, self)

在上面的代码中,我们通过绘制背景颜色来模拟按压效果。如果组合框是可编辑状态,则使用白色作为背景颜色;如果组合框是不可编辑状态,则使用灰色作为背景颜色。最后通过initStyleOption方法和drawComplexControl方法绘制出组合框的样式。

使用自定义的组合框,只需要将之前的QComboBox改为CustomComboBox即可:

from PyQt5.QtWidgets import QApplication, QWidget
from .custom_combo_box import CustomComboBox

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

        combo_box = CustomComboBox(self)
        combo_box.setEditable(False)  # 设置为不可编辑
        combo_box.addItem("Option 1")
        combo_box.addItem("Option 2")
        combo_box.addItem("Option 3")

下面给出另一个示例:

class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
                QLineEdit {
                    border: 1px solid #ccc;
                    border-radius: 4px;
                }
                QLineEdit:focus {
                    border-color: rgb(61, 174, 233);
                }
            """)

    def focusInEvent(self, e):
        super(MyLineEdit, self).focusInEvent(e)
        palette = self.palette()
        palette.setColor(QPalette.Base, QColor(255, 255, 255))
        self.setPalette(palette)

    def focusOutEvent(self, e):
        super(MyLineEdit, self).focusOutEvent(e)
        palette = self.palette()
        palette.setColor(QPalette.Base, QColor(220, 220, 220))
        self.setPalette(palette)

上面的代码定义了一个自定义的QLineEdit类,实现了在获取焦点时将背景颜色设置为白色,在失去焦点时将背景颜色设置为灰色。同样,我们可以通过类似的方式实现自定义的组合框。