Python 如何将样式表应用于 PyQt 中的自定义小部件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22504421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply style sheet to a custom widget in PyQt
提问by Anke_Pet
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setFixedWidth(200)
self.setFixedHeight(200)
stylesheet = \
".QWidget {\n" \
+ "border: 20px solid black;\n" \
+ "border-radius: 4px;\n" \
+ "background-color: rgb(255, 255, 255);\n" \
+ "}"
self.setStyleSheet(stylesheet)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
I want to add a border to a custom widget with style sheet, but the style sheet does not seem to work, anything wrong?
我想为带有样式表的自定义小部件添加边框,但样式表似乎不起作用,有什么问题吗?
采纳答案by ekhumoro
Firstly: add an actual widget to your example:
首先:在您的示例中添加一个实际的小部件:
self.widget = QWidget(self)
layout = QVBoxLayout(self)
layout.addWidget(self.widget)
Secondly: do yourself a favour, and use triple-quotes:
其次:帮自己一个忙,并使用三重引号:
self.widget.setStyleSheet("""
QWidget {
border: 20px solid black;
border-radius: 10px;
background-color: rgb(255, 255, 255);
}
""")
The dot-selector in your example is redundant. What it does is specify that only instances of QWidgetitself will be selected, as opposed to sub-classes of QWidget. See the StyleSheet Syntaxguide in the Qt docs.
您示例中的点选择器是多余的。它的作用是指定仅QWidget选择其自身的实例,而不是QWidget. 请参阅Qt 文档中的样式表语法指南。
回答by Eric Petersen
In your project folder add a basic CSS file mystylesheet.css. Mutli-language editors like Atom are best for this type of things. The syntax highlighting works properly if you keep it named a CSS file.
在您的项目文件夹中添加一个基本的 CSS 文件 mystylesheet.css。像 Atom 这样的多语言编辑器最适合这类事情。如果将其命名为 CSS 文件,则语法突出显示可以正常工作。
Then drop the dot; qt knows what you mean.
然后放下点;qt 知道你的意思。
mystylesheet.css
mystylesheet.css
QWidget {
border: 20px solid black;
border-radius: 10px;
background-color: rgb(255, 255, 255);
}
anyQelement.setStyleSheet(open('mystylesheet.css').read())

