0

I have defined a custom Rectangle widget and am trying to assign a custom stylesheet to it. Can anybody help and tell why the below-quoted code does not paint Rectangle in red? Options 1. and 3. in the code show a white color which is inherited from QWidget, I suppose. And, option 2. makes my widget hidden, probably because Window's stylesheet dominates.

import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget

class Rectangle(QWidget):

  def __init__(self, parent):
      super(Rectangle, self).__init__(parent)
      self.setGeometry(20, 20, 200, 400)
      self.setAutoFillBackground(True)
     
      # 1.
      self.setObjectName = "Rectangle#rect"
      self.setStyleSheet("Rectangle#rect {background-color: red;}")

      # 2.
      # self.setStyleSheet("Rectangle {background-color: red;}")
     
      # 3.
      # self.setStyleSheet("{background-color: red;}")


class Window(QMainWindow):

    def __init__(self):
        super(Window, self).__init__()

        self.setGeometry(200, 200, 300, 500)
        self.setWindowTitle("Test")
        self.setAutoFillBackground(True)      
        self.setStyleSheet("Window {background-color: blue;}")

        rect = Rectangle(self)
        self.show()

def run():
    app = QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

0 Answers0