how to use QHBoxLayout and QVBoxLayout in PySdie2

it is very simple and easy to layout widgets with QH(V)BoxLayout.
in this page, I will introduce how to use them with example code.

have a look at below example code.


from PySide2.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QPushButton, QWidget

app = QApplication([])

widget = QWidget()
btn1 = QPushButton("btn1")
btn2 = QPushButton("btn2")
btn3 = QPushButton("btn3")
btn4 = QPushButton("btn4")
btn5 = QPushButton("btn5")

hLayout = QHBoxLayout()
hLayout.addWidget(btn1)
hLayout.addWidget(btn2)
hLayout.addWidget(btn3)
hLayout.addWidget(btn4)
hLayout.addWidget(btn5)

widget.setLayout(hLayout)
widget.show()

app.exec_()


first of all, we have to import widgets that we will use. in this example code, I will use QApplication, QVBoxLayout, QHBoxLayout, QPushButton and QWidget. so I imported them. like below.


from PySide2.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QPushButton, QWidget

and then, I created QApplication object. and I created QWidget object that will be our main window widget. every widget can have layout that arrange the children of the widget.


widget = QWidget()

I created 5 buttons. the constructor's parameter will be label of button.


btn1 = QPushButton("btn1")
btn2 = QPushButton("btn2")
btn3 = QPushButton("btn3")
btn4 = QPushButton("btn4")
btn5 = QPushButton("btn5")

I will add the button widgets to QHBoxLayout that arrange the widgets horizontally.


hLayout = QHBoxLayout()
hLayout.addWidget(btn1)
hLayout.addWidget(btn2)
hLayout.addWidget(btn3)
hLayout.addWidget(btn4)
hLayout.addWidget(btn5)

lastly, I set the QHBoxLayout to our main widget's layout. and then, I make the widget shown. finally, I execute the main loop by calling app.exec_()


widget.setLayout(hLayout)
widget.show()

app.exec_()

the result is like below.


the way to use QVBoxLayout is very similar to QHBoxLayout.
just modify the line that create QHBoxLayout object to QVBoxLayout.


hLayout = QVBoxLayout()

the result is like below








Comments

Popular posts from this blog

making menubar and menu on QML

QSizePolicy Fixed example in pyside2

let's start QML programming with PySide2