I'm trying to get the button to be centered beneath the label using PyQt6. I would also like it to work when resizing the window. Thank you in advance!
layout = QVBoxLayout()
self.welcome_label = QLabel("Welcome to Application!", self)
self.welcome_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.welcome_label.setFont(QFont('Arial', 30))
layout.addWidget(self.welcome_label)
self.start_button = QPushButton('Start')
self.start_button.setFixedSize(QSize(100,30))
layout.addWidget(self.start_button)
self.setLayout(layout)
Current look and arrow to where I would like the button to go:
I have tried adding spacers, deleting margins, using screen size information to change geometry location but have had no luck.
This will do it without any sub-layouts:
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton
class Window(QWidget):
def __init__(self):
super().__init__()
self.resize(500, 500)
welcome_label = QLabel("Welcome to Application!")
welcome_label.setFont(QFont('Arial', 30))
start_button = QPushButton('Start')
layout = QVBoxLayout(self)
layout.addStretch()
layout.addWidget(welcome_label, alignment=Qt.AlignmentFlag.AlignCenter)
layout.addWidget(start_button, alignment=Qt.AlignmentFlag.AlignCenter)
layout.addStretch()
if __name__ == '__main__':
app = QApplication([])
window = Window()
window.show()
app.exec()
You use addStretch()
twice to centre the label and button vertically and keep them together.
You use addWidget()
with the alignment
argument to centre the widgets horizontally.
AlignCenter
also makes sure that the button doesn't expand horizontally to the full width of the widget.