How to stretch a pixmap to the edge of the window?

177 views Asked by At

I have a PyQt window. The window is made up of a VBoxLayout within a HBoxLayout and is displayed below.

This is what the window currently looks like:

enter image description here

However, I want the image to stretch to the edge of the window like in the edited image below:

enter image description here

I have tried setting the padding and contentsmargin of the window to zero but this messses up the spacing in the rest of the HBoxLayout. Is there any way to stretch this image to fill the window edges without messing up the spacing in the rest of my layout.

Minimal reproducible example:

class MainWindow(QMainWindow):
def __init__(self):
    super(MainWindow, self).__init__()

    self.CentralWidget = QWidget()
    self.setCentralWidget(self.CentralWidget)
    self.VBL1 = QVBoxLayout()

    LogoLabel = QLabel()
    LogoPixmap = QPixmap("Resources/Logo.png").scaledToHeight(30)
    LogoLabel.setPixmap(LogoPixmap)
    LogoLabel.setAlignment(Qt.AlignCenter)
    self.VBL1.addWidget(LogoLabel)

    self.WelcomeLabel = QLabel("Welcome Back!")
    self.VBL1.addWidget(self.WelcomeLabel)

    UsernameLabel = QLabel("Username")
    self.VBL1.addWidget(UsernameLabel)

    self.UsernameTB = QLineEdit()
    self.VBL1.addWidget(self.UsernameTB)

    PasswordLabel = QLabel("Password")
    self.VBL1.addWidget(PasswordLabel)

    self.PasswordTB = QLineEdit()
    self.VBL1.addWidget(self.PasswordTB)

    self.SignInBTN = QPushButton("Sign In")
    self.VBL1.addWidget(self.SignInBTN)

    self.CreateAccountBTN = QPushButton("Create An Account")
    self.VBL1.addWidget(self.CreateAccountBTN)

    # Art Label stores the image I want to stretch to the edges
    ArtLabel = QLabel()
    ArtPixmap = QPixmap("Stylesheet/LoginArt.jpg").scaledToHeight(250)
    ArtLabel.setPixmap(ArtPixmap)

    self.HBL1 = QHBoxLayout()
    self.HBL1.addLayout(self.VBL1)
    self.HBL1.addWidget(ArtLabel)
    self.CentralWidget.setLayout(self.HBL1)
1

There are 1 answers

0
scopchanov On BEST ANSWER

Use self.HBL1.setContentsMargins(0, 0, 0, 0).

If doing this leaves you with too small space around the widgets on the left, set the desired space with self.VBL1.setContentsMargins(22, 22, 22, 22).

Additionally, if you want to preserve the spacing between the image and the widgets, specify a different value for the right margin of the VBL1.