pythonpyqt5qvboxlayout

Position Label In Center Without Filling The Entire Layout in PyQt5


I'm creating an app in PyQt5 and I want my label to be in the center of the window, without it filling the entire space. So Some Label should be where Hello is as seen below, but I don't want Some Label to fill up the entire space.

Image

I thought perhaps I could put Some Label in a container that fills up the entire space, and center Some Label inside the container just like Hello, but I just can't get this to work.

Here's my code:

def main():
    app = QApplication(sys.argv)
    win = QWidget()

    win.setFixedSize(225,150)

    label1 = QLabel("Hello")
    label1.setStyleSheet('border: 1px solid red')

    label2 = QLabel("Some Label", label1)
    label2.setAlignment(QtCore.Qt.AlignCenter)
    label2.setStyleSheet('background: red')

    label1.setAlignment(QtCore.Qt.AlignCenter)

    layout = QVBoxLayout()
    layout.addWidget(label1)

    win.setLayout(layout)

    win.show()
    sys.exit(app.exec_())

main()

Any ideas?


Solution

  • You just need to set the alignment on the layout:

    from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
    from PyQt5.QtCore import Qt
    
    app = QApplication([])
    win = QWidget()
    win.setFixedSize(225, 150)
    
    label1 = QLabel("Hello")
    label1.setStyleSheet('border: 1px solid red')
    
    layout = QVBoxLayout(win)
    layout.setAlignment(Qt.AlignCenter)
    layout.addWidget(label1)
    
    win.show()
    app.exec()