PyQt5组合框 不可编辑时的不同边框宽度

  • Post category:Python

PyQt5是基于Qt框架的Python GUI开发库,可以用于创建各种图形用户界面应用程序,其中组合框(QComboBox)是一种常用的界面元素。在使用QComboBox时,经常需要禁用用户编辑,这时候会发现当下拉框未展开时,它的边框宽度和已展开的情况下不同,下面详细讲解如何解决这个问题。

1.使用QComboBox.setStyleSheet()方法

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QComboBox

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        combo = QComboBox(self)
        combo.setGeometry(50, 50, 150, 30)

        # 设置不可编辑
        combo.setEditable(False)
        # 设置下拉框中的选项
        combo.addItem('Option 1')
        combo.addItem('Option 2')

        # 设置样式表
        combo.setStyleSheet("QComboBox::down-arrow {border: 1px solid black;}"
                            "QComboBox::down-arrow:on {border: 1px solid black;}"
                            "QComboBox::drop-down {border: 1px solid black;}")

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QComboBox Style Sheet')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

这里使用了样式表(stylesheet)来设置下拉框的边框宽度。“QComboBox::down-arrow”表示展开下拉框时的箭头,”QComboBox::down-arrow:on”表示箭头已被点击,”QComboBox::drop-down”为下拉框部分,默认边框宽度为0,可以通过在上述选择器后加上”border: 1px solid black;”来设置边框宽度和颜色。

2.使用QProxyStyle继承原生样式

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QComboBox, QProxyStyle

class CustomStyle(QProxyStyle):
    def subControlRect(self, control, option, subControl, widget=None):
        r = QProxyStyle.subControlRect(self, control, option, subControl, widget)
        if control == QProxyStyle.SC_ComboBoxArrow:
            if subControl == QProxyStyle.SC_ComboBoxArrow:
                r = r.adjusted(0, 0, 1, 0)
        return r

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        combo = QComboBox(self)
        combo.setGeometry(50, 50, 150, 30)

        # 设置不可编辑
        combo.setEditable(False)
        # 设置下拉框中的选项
        combo.addItem('Option 1')
        combo.addItem('Option 2')

        # 继承原生样式
        customstyle = CustomStyle()
        combo.setStyle(customstyle)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QComboBox Style Sheet')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

这种方法使用了自定义的QProxyStyle来继承原生样式,并在其基础上微调样式。具体来说,实现CustomStyle类并重载其中的subControlRect()方法,它会在下拉框展开前被调用,检查是不是要调整rect大小。如果检测到control是QProxyStyle.SC_ComboBoxArrow,并且subControl是QProxyStyle.SC_ComboBoxArrow,则向右边推一个像素来调整边框宽度。

通过上述两种方法,可以轻松解决PyQt5组合框不可编辑时边框宽度不同的问题。