我正在尝试更改组合框背景的颜色。我希望它是白色的,但是我不能使它具有不同于灰色的任何颜色。上面的图片是我得到的,下面的图片是我想要的。
这是我的代码:
from PyQt5 import QtWidgets, QtGui
class combodemo(QtWidgets.QWidget):
def __init__(self, parent = None):
super(combodemo, self).__init__(parent)
layout = QtWidgets.QHBoxLayout()
self.cb = QtWidgets.QComboBox()
self.cb.addItem("1")
self.cb.addItem("2")
pal = self.cb.palette()
pal.setColor(self.cb.backgroundRole(),QtGui.QColor(255,255,255))
self.cb.setPalette(pal)
self.cb.setAutoFillBackground(True)
layout.addWidget(self.cb)
self.setLayout(layout)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
ex = combodemo()
ex.show()
app.exec_()
答案 0 :(得分:3)
您必须更改QPalette::Button
角色的颜色:
from PyQt5 import QtWidgets, QtGui
class combodemo(QtWidgets.QWidget):
def __init__(self, parent = None):
super(combodemo, self).__init__(parent)
layout = QtWidgets.QHBoxLayout(self)
self.cb = QtWidgets.QComboBox()
self.cb.addItems(["1", "2"])
pal = self.cb.palette()
pal.setColor(QtGui.QPalette.Button, QtGui.QColor(255,255,255))
self.cb.setPalette(pal)
layout.addWidget(self.cb)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
ex = combodemo()
ex.show()
sys.exit(app.exec_())
在Windows中,您需要:
app.setStyle("fusion")
答案 1 :(得分:0)
为避免更改整个应用程序的样式,我根据How to set background color of QComboBox button?使用了样式表。
请注意,如文章中所述,此样式的样式为“整个下拉列表以模仿本机外观,但这样做不好,也不健壮(并且不便于移植)”。但是,由于更改应用程序的样式影响更大,因此该方法可以满足我的目的。
这是我的样式表:
QComboBox QAbstractItemView {
border: 1px solid grey;
background: white;
selection-background-color: blue;
}
QComboBox {
background: red;
}
和代码:
from PyQt5 import QtWidgets, QtGui
class combodemo(QtWidgets.QWidget):
def __init__(self, parent = None):
super(combodemo, self).__init__(parent)
layout = QtWidgets.QHBoxLayout()
self.cb = QtWidgets.QComboBox()
self.cb.addItem("1")
self.cb.addItem("2")
cbstyle = "QComboBox QAbstractItemView {"
cbstyle += " border: 1px solid grey;"
cbstyle += " background: white;"
cbstyle += " selection-background-color: blue;"
cbstyle += " }"
cbstyle += " QComboBox {"
cbstyle += " background: white;"
cbstyle += "}"
self.cb.setStyleSheet(cbstyle)
layout.addWidget(self.cb)
self.setLayout(layout)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
ex = combodemo()
ex.show()
app.exec_()