如何解决Qt:为什么 qss 文件中只有一种样式有效
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class Win(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet(
'QWidget{background: rgb(150,150,150);};'
'QPushButton{background-color: rgb(255,0); font-size: 100px;};'
'QLineEdit{background-color: yellow; font-size:5px;};'
)
layout = qgridLayout()
self.setLayout(layout)
lay1 = QVBoxLayout()
btn1 = QPushButton('btn')
lay1.addWidget(btn1)
layout.addLayout(lay1,1,1)
lay2 = QVBoxLayout()
label1 = QLabel('label')
lay2.addWidget(label1)
layout.addLayout(lay2,1)
lay3 = QVBoxLayout()
edit = QLineEdit('edit')
lay3.addWidget(edit)
layout.addLayout(lay3,1)
layout.setRowStretch(0,1)
layout.setRowStretch(1,1)
layout.setColumnStretch(0,1)
layout.setColumnStretch(1,1)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Win()
win.show()
sys.exit(app.exec_())
我使用```setStyleSheet`来控制我的窗口,结果是:
我们可以发现只有 QWidget{background: rgb(150,150);}
有效。我想让QPushButton
的背景色通过'QPushButton{background-color: rgb(255,0); font-size: 100px;};'
变红,而QPushButton
的背景色实际上不是红色。
然后,如果我注释 'QWidget{background: rgb(150,150);};'
,并且新代码是:
...
self.setStyleSheet(
# 'QWidget{background: rgb(150,0); font-size: 100px;};'
'QLineEdit{background-color: yellow; font-size:5px;};'
)
...
现在,结果是:
我们可以发现 'QPushButton{background-color: rgb(255,0); font-size: 100px;};'
有效,但 'QLineEdit{background-color: yellow; font-size:5px;};'
仍然无效。
我怎样才能让这三种风格起作用?
'QWidget{background: rgb(150,150);};'
'QPushButton{background-color: rgb(255,0); font-size: 100px;};'
'QLineEdit{background-color: yellow; font-size:5px;};'
解决方法
您在 QSS 语法中有错误,因为在 }
之后不应该有 ;
:
self.setStyleSheet(
"QWidget{background: rgb(150,150,150);}"
"QPushButton{background-color: rgb(255,0); font-size: 100px;}"
"QLineEdit{background-color: yellow; font-size:5px;}"
)
此外,许多样式在使用 QSS 时表现不同,例如我使用融合样式获得了正确的结果:
app.setStyle("fusion")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。