0

I am new to Python learning to code again after a long break. So forgive if this is trivial (which it almost certainly is).

I am trying to create a subclass of QWidget to make it easier to set a background colour (and other stuff in the future of course).

I have two examples, one works and the other does not. I would like to 'fix' the one that does not.

The task is to create a window with a red background.

(Note. I am english, hence the use of colour not color in my customization)

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        cw1 = QWidget()
        cw1.setAutoFillBackground(True)
        cw1.setStyleSheet("background-color: Red;")

        self.setCentralWidget(cw1)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

In this version I am subclassing QWidget to allow the colour parameter

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

class ColourW(QWidget):

    def __init__(self, colour, *args, **kwargs):
        super(ColourW, self).__init__(*args, **kwargs)

        self.setAutoFillBackground(True)
        self.setStyleSheet("background-color: {colour};")

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        cw1 = ColourW('red')
        self.setCentralWidget(cw1)


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

Any help much appreciated.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Paul West
  • 81
  • 8
  • 1) change to `self.setStyleSheet(f"background-color: {colour};")` 2) add `self.setAttribute(Qt.WA_StyledBackground, True)` – eyllanesc Jan 02 '20 at 14:49
  • Thanks. Solved! The first one was a stupid mistake, I know that one! The second one I never would have got without help. Thanks! – Paul West Jan 02 '20 at 15:01

0 Answers0