Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Losing my (mind) background



  • I think there is something fundamental missing in my understanding. I'm trying to get a window with a graphic on one side and a couple of buttons on the other. If I instantiate a PictureWidget by itself in "if _name..." it works expected: a window is created with a background from background.png. But if I create my_picture_widget (along with my_button_widget) and display these as elements of MyWindow, the background does not appear. What am I missing? What is the hole in my understanding?

    (My apologies that this is PyQt5 and not pyside, but this seems to be the place to get the highest quality answers).

    Thanks,
    Mike

    code_text
    
    from PyQt5.QtGui import QPixmap, QPalette, QBrush
    
    class MyWindow(QWidget):
    
        def __init__(self):
            super(MyWindow, self).__init__()
    
            my_button_widget  = Button_Widget()
            my_picture_widget = Picture_Widget()
    
            layout = QHBoxLayout()
            layout.addWidget(my_button_widget)
            layout.addWidget(my_picture_widget)
    
            self.setLayout(layout)
    
    class Button_Widget(QWidget):
        def __init__(self):
            super(Button_Widget, self).__init__()
    
            b1 = QPushButton("Foo")
            b2 = QPushButton("Bar")
    
            layout = QVBoxLayout()
            layout.addWidget(b1)
            layout.addWidget(b2)
            self.setLayout(layout)
    
    class Picture_Widget(QWidget):
        def __init__(self):
            super(Picture_Widget, self).__init__()
    
            bkgnd = QPixmap("background.png")
    
            self.setFixedSize(bkgnd.width(), bkgnd.height())
    
            self.palette = QPalette()
            self.palette.setBrush(QPalette.Background, QBrush(bkgnd))
            self.setPalette(self.palette)
    
            foo = QPushButton("Hello")
            layout = QHBoxLayout()
            layout.addWidget(foo)
            self.setLayout(layout)
    
    #------------------------------------------------------------------------
    
        import sys
    
        app = QApplication(sys.argv)
    
        win = MyWindow()
        win.show()
    
        #pic = Picture_Widget()     # Uncomment these two to show
        #pic.show()                 # that Picture_Widget() works.
    
        sys.exit(app.exec_())
    

    code_text


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Use Window in place of Background for the palette and add self.setAutoFillBackground(True) to the widget.



  • That (of course) works perfectly. In the future I'll be more careful using StackExchange examples from -6- years ago. Thank you!


  • Lifetime Qt Champion

    The number of year may or may not be irrelevant, but double checking with the documentation is always a good idea :-)


Log in to reply