PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 17, 2022

[FIXED] How to adjust the geometry of widgets added in vertical box layout in pyqt5

 November 17, 2022     button, pyqt5, python, vertical-alignment     No comments   

Issue

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:

enter image description here

How can I adjust the geometry of the buttons to move above. Expected output like below:

enter image description here

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_())

Solution

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_())


Answered By - jairoar
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing