Pyqt: How to apply a stylesheet to a custom widget

# -*- 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 a list of styles, but the stylesheet doesn't work, is something wrong?

+7
source share
2 answers

First: add a valid widget to your example:

    self.widget = QWidget(self)
    layout = QVBoxLayout(self)
    layout.addWidget(self.widget)

Second: do yourself a favor and use triple quotes:

    self.widget.setStyleSheet("""
        .QWidget {
            border: 20px solid black;
            border-radius: 10px;
            background-color: rgb(255, 255, 255);
            }
        """)

NB: the point selector in your example is redundant. What he does is indicate that only instances will be selected QWidget, not subclasses QWidget. See the StyleSheet syntax guide in Qt docs.

+21
source

CSS mystylesheet.css. , Atom, . , CSS .

; Qt , .

mystylesheet.css

QWidget {
    border: 20px solid black;
    border-radius: 10px;
    background-color: rgb(255, 255, 255);
}
anyQelement.setStyleSheet(open('mystylesheet.css').read())
+1

Source: https://habr.com/ru/post/1532461/


All Articles