![](/img/trans.png)
[英]How to make widgets stack on top of each other using QScrollArea with Vertical layout in PyQt5?
[英]How to adjust the geometry of widgets added in vertical box layout in pyqt5
我創建了一個vertical
布局的pyqt5
窗口。 在這個垂直布局中,我添加了 2 個按鈕。 默認情況下,它們垂直對齊,如下所示:
如何調整按鈕的幾何形狀以在上方移動。 預期輸出如下:
所以如果我添加第三個按鈕,它會低於按鈕 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_())
您需要設置布局的對齊方式並在您添加的小部件之間添加一些間距,如下所示:
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.