pyqt: How to apply style sheet to a custom widget

坚强是说给别人听的谎言 提交于 2019-11-30 04:02:51

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);
            }
        """)

NB: the dot-selector in your example is redundant. What it does, is specify that only instances of QWidget itself will be selected, as opposed to sub-classes of QWidget. See the StyleSheet Syntax guide in the Qt docs.

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.

Then drop the dot; qt knows what you mean.

mystylesheet.css

QWidget {
    border: 20px solid black;
    border-radius: 10px;
    background-color: rgb(255, 255, 255);
}
anyQelement.setStyleSheet(open('mystylesheet.css').read())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!