python - 如何使用样式表设置 qwidget 的背景颜色?
问题描述
Qt 样式表有一些我似乎不明白的地方。我只想将小部件的背景颜色设置为白色。但由于某种原因,背景颜色实际上只出现在我的小部件的孩子中。
我试图添加self.setAutoFillBackground(True)
到我的代码中,但没有成功。
我还尝试从https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget调色解决方案。它有效,但前提是我没有设置底部边框所需的样式表。
class TopLabelNewProject(qt.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
layout = qt.QHBoxLayout(self)
layout.setContentsMargins(40, 0, 32, 0)
self.setLayout(layout)
self.setFixedHeight(80)
self.setStyleSheet("""
background-color: white;
border-bottom: 1px solid %s;
""" % colors.gray)
self.label = qt.QLabel("Dashboard")
self.label.setStyleSheet("""
QLabel {
font: medium Ubuntu;
font-size: 20px;
color: %s;
}""" % colors.gray_dark)
layout.addWidget(self.label, alignment=qt.Qt.AlignLeft)
self.newProjectButton = Buttons.DefaultButton("New project", self)
layout.addWidget(self.newProjectButton, alignment=qt.Qt.AlignRight)
注意:Buttons.DefaultButton 只是一个带有自定义样式表的 QPushButton。
这就是我想要实现的,带有标签和按钮的白色标题栏:
但只有标签有白色背景。
解决方案
试试看:
import sys
from PyQt5 import Qt as qt
class TopLabelNewProject(qt.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
layout = qt.QHBoxLayout(self)
layout.setContentsMargins(40, 0, 32, 0)
self.setLayout(layout)
self.setFixedHeight(80)
self.label = qt.QLabel("Dashboard")
layout.addWidget(self.label, alignment=qt.Qt.AlignLeft)
# self.newProjectButton = Buttons.DefaultButton("New project", self)
self.newProjectButton = qt.QPushButton("New project", self)
layout.addWidget(self.newProjectButton, alignment=qt.Qt.AlignRight)
style = '''
QWidget {
background-color: white;
}
QLabel {
font: medium Ubuntu;
font-size: 20px;
color: #006325;
}
QPushButton {
background-color: #006325;
color: white;
min-width: 70px;
max-width: 70px;
min-height: 70px;
max-height: 70px;
border-radius: 35px;
border-width: 1px;
border-color: #ae32a0;
border-style: solid;
}
QPushButton:hover {
background-color: #328930;
}
QPushButton:pressed {
background-color: #80c342;
}
'''
if __name__ == '__main__':
app = qt.QApplication(sys.argv)
app.setStyleSheet(style)
ex = TopLabelNewProject()
ex.show()
sys.exit(app.exec_())
推荐阅读
- ios - 从 Xcode 连接 GidSignInButton 时出错
- javascript - 解决承诺的两种方式之间的区别
- circleci - CircleCI - 加速共享 Docker 映像的作业
- salesforce - Mule4:使用 OffSet 和 LIMIT 实现 parallel-foreach 来查询 Saleforces
- monitor - 在 Windows 10 中阻止部分屏幕损坏显示器
- python - 带有 MQTT 订阅的 Python Flask 服务器 on_message 不工作
- python - 循环遍历唯一条目
- php - 如何捕获 SSH 命令输出包含子字符串?- Laravel 5.8
- python - 消息:“chromedriver”可执行文件需要在 PATH 中。请参阅 https://sites.google.com/a/chromium.org/chromedriver/home
- javascript - Select2 TokenSeparators 不适用于 S2MultiCheckboxes 扩展