📌  相关文章
📜  PyQt5 - 为 ComboBox 的 lineedit 部分添加边框(1)

📅  最后修改于: 2023-12-03 15:33:51.218000             🧑  作者: Mango

PyQt5 - 为 ComboBox 的 lineedit 部分添加边框

在 PyQt5 中,ComboBox 组件中的 lineedit 部分默认没有边框,如果需要添加边框,有以下几种方法:

方法一:使用 style sheet
from PyQt5.QtWidgets import QApplication, QComboBox
from PyQt5.QtGui import QPalette, QColor

app = QApplication([])
combo = QComboBox()
combo.setEditable(True)
combo.lineEdit().setStyleSheet('border: 1px solid gray;')
combo.show()
app.exec_()

使用 setStyleSheet 方法为 lineEdit 添加边框样式,setEditable(True) 可以使 lineEdit 可以编辑。

方法二:使用 QStyle
from PyQt5.QtWidgets import QApplication, QComboBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette, QColor

app = QApplication([])
combo = QComboBox()
combo.setEditable(True)
palette = QPalette()
palette.setColor(QPalette.Base, QColor(255, 255, 255))
palette.setColor(QPalette.Text, QColor(0, 0, 0))
combo.lineEdit().setPalette(palette)
combo.lineEdit().setAlignment(Qt.AlignCenter)
option = combo.lineEdit().style().standardOption(QComboBox.SO_Frame)
combo.lineEdit().setStyleSheet(combo.lineEdit().style().subControlStyleSheet(QStyle.CC_ComboBox, 
                                                option, QStyle.SC_ComboBoxEditField, combo.lineEdit()))
combo.show()
app.exec_()

使用 QStyle 可以获取 lineEdit 的样式选项(QComboBox.SO_Frame),然后使用 subControlStyleSheet 方法获取边框样式,并设置到 lineEdit 上。

方法三:自定义 QComboBox
from PyQt5.QtWidgets import QApplication, QComboBox
from PyQt5.QtCore import Qt

class ComboBox(QComboBox):
    def __init__(self, parent=None):
        super(ComboBox, self).__init__(parent)
        self.setEditable(True)
        self.lineEdit().setAlignment(Qt.AlignCenter)
        self.lineEdit().setStyleSheet('border: 1px solid gray;')

app = QApplication([])
combo = ComboBox()
combo.show()
app.exec_()

继承 QComboBox 并重写 __init__ 方法,自定义 ComboBox 的样式,以实现 lineedit 部分的边框样式。注:此方法只适用于 Python 开发,不适用于 Qt Designer。