pyqt: How to apply style sheet to a custom widget

2019-02-02 18:04发布

# -*- 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?

标签: python pyqt qss
2条回答
姐就是有狂的资本
2楼-- · 2019-02-02 18:13

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.

查看更多
祖国的老花朵
3楼-- · 2019-02-02 18:29

In your project folder add a basic css file mystylesheet.css. Mutli-language editors like atom are best for these type of things. The syntax highlighting works properly if you keep it named a css file.

Then drop the dot, qt knows that you mean.

CSS:
QWidget {
    border: 20px solid black;
    border-radius: 10px;
    background-color: rgb(255, 255, 255);
}

Python:
anyQelement.setStyleSheet(open('mystylesheet.css').read())
查看更多
登录 后发表回答