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

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Anke_Pet
  • 354
  • 1
  • 3
  • 10
  • have you tried removing the period before QWidget? – justengel Mar 19 '14 at 11:57
  • although you did receive an answer that seems adequate, please consider being more specific than "does not work as expected", by saying (even now that your question has been answered) what specifically did you expect and what portion of this did not work. – Oliver Mar 20 '14 at 21:32
  • Ok, I'll do better next time~ – Anke_Pet Mar 21 '14 at 04:40

2 Answers2

37

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 QWidget itself will be selected, as opposed to sub-classes of QWidget. See the StyleSheet Syntax guide in the Qt docs.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
12

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())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Eric Petersen
  • 121
  • 1
  • 4
  • 3
    Would it be better to use with open("mystylesheet.css", 'r') as file: sheet = file.read() anyQelement.setStyleSheet(sheet) to ensure the file is closed properly? – rwalroth Jun 10 '20 at 23:20