📅  最后修改于: 2023-12-03 15:33:54.761000             🧑  作者: Mango
在 PyQt5 中,当鼠标悬停在 lineedit 部分时,边框的宽度会发生变化,这对于不可编辑的组合框来说是不需要的。本文将介绍如何解决这个问题。
要解决这个问题,需要提供一个辅助样式表。可以使用以下代码:
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 15px;
border-left-width: 1px;
border-left-color: darkgray;
border-left-style: solid;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
QComboBox::down-arrow {
image: url(down_arrow.png);
}
然后,将该样式表设置为组合框的样式表:
self.setStyle(QStyleFactory.create("Windows"))
self.setStyleSheet("""
QComboBox QAbstractItemView {
border: 2px solid darkgray;
background-color: white;
selection-background-color: lightgray;
selection-color: black;
}
QComboBox::item:selected {
background-color: lightgray;
color: black;
}
QComboBox::item:disabled {
color: gray;
}
QComboBox::down-arrow {
image: url(down_arrow.png);
}
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 15px;
border-left-width: 1px;
border-left-color: darkgray;
border-left-style: solid;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
""")
这样就能解决鼠标悬停时 lineedit 部分的边框宽度不同的问题了。
完整的代码如下:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class ComboBoxDemo(QWidget):
def __init__(self, parent=None):
super(ComboBoxDemo, self).__init__(parent)
layout = QVBoxLayout()
self.comboBox = QComboBox()
self.comboBox.addItems(['item1', 'item2', 'item3'])
self.comboBox.setDisabled(True)
layout.addWidget(self.comboBox)
self.setLayout(layout)
self.setStyle(QStyleFactory.create("Windows"))
self.setStyleSheet("""
QComboBox QAbstractItemView {
border: 2px solid darkgray;
background-color: white;
selection-background-color: lightgray;
selection-color: black;
}
QComboBox::item:selected {
background-color: lightgray;
color: black;
}
QComboBox::item:disabled {
color: gray;
}
QComboBox::down-arrow {
image: url(down_arrow.png);
}
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 15px;
border-left-width: 1px;
border-left-color: darkgray;
border-left-style: solid;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
""")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
demo = ComboBoxDemo()
demo.show()
sys.exit(app.exec_())