[英]How to adjust the geometry of widgets added in vertical box layout in pyqt5
I have created a pyqt5
window which has a vertical
layout.我创建了一个
vertical
布局的pyqt5
窗口。 Inside this vertical layout, I have added 2 buttons.在这个垂直布局中,我添加了 2 个按钮。 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:所以如果我添加第三个按钮,它会低于按钮 2。下面是代码:
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_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.