I have created a pyqt5
window which has a vertical
layout. Inside this vertical layout, I have added 2 buttons. By default these are vertically aligned like below:
How can I adjust the geometry of the buttons to move above. Expected output like below:
so that if I add 3rd button, it goes below button 2. Below is the code:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
layout = QVBoxLayout()
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
button1 = QPushButton('Button 1', self)
layout.addWidget(button1)
button2 = QPushButton('Button 2', self)
layout.addWidget(button2)
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
You need to set the alignment of your layout and add some spacing between the widgets you added, like this:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton
from PyQt5 import QtCore
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
layout = QVBoxLayout()
#set spacing between your widgets
layout.setSpacing(5)
#set alignment in your vertical layout
layout.setAlignment(QtCore.Qt.AlignTop)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
button1 = QPushButton('Button 1', self)
layout.addWidget(button1)
button2 = QPushButton('Button 2', self)
layout.addWidget(button2)
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
Thanks. I am actually designing the UI from qt desginer. Is it possible to set alignment of layout in qt designer.
I think yes, check this: Designer Alignment aditionally you can set the size of your VBox as fixed and the widgets inside wont move.