所以我用QVBoxLayout创建了一个简单的PyQt5应用程序。显然,我添加的每个按钮从一端延伸到另一端,它们全部堆叠在一起。如何在QVBoxLayout上添加按钮,这些按钮是我屏幕上的一组三个小按钮?
答案 0 :(得分:1)
所以你的按钮需要QHBoxLayout
,嵌套在QVBoxLayout
:
class Main(QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.vLayout = QVBoxLayout(self.centralWidget)
self.buttonsWidget = QWidget()
self.buttonsWidgetLayout = QHBoxLayout(self.buttonsWidget)
self.buttons = [QPushButton(c) for c in 'ABC']
for button in self.buttons:
self.buttonsWidgetLayout.addWidget(button)
self.placeHolder = QWidget()
self.placeHolder.setMinimumWidth(480)
self.placeHolder.setMinimumHeight(320)
self.placeHolder.setStyleSheet('* {background: red;}')
self.vLayout.addWidget(self.placeHolder)
self.vLayout.addWidget(self.buttonsWidget)
答案 1 :(得分:-1)
为确保元素不被拉伸,您可以使用特殊元素 QSpacerItem元素。
试一试:
from PyQt5 import Qt
class Widget(Qt.QWidget):
def __init__(self):
super().__init__()
layout = Qt.QVBoxLayout(self)
btn_layout = Qt.QHBoxLayout()
# !!!
btn_layout.addItem(Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Minimum))
btn1 = Qt.QPushButton("Button 1")
btn2 = Qt.QPushButton("Button 2")
btn3 = Qt.QPushButton("Button 3")
btn_layout.addWidget(btn1)
btn_layout.addWidget(btn2)
btn_layout.addWidget(btn3)
table = Qt.QTableWidget()
table.setRowCount(5)
table.setColumnCount(5)
layout.addWidget(table)
layout.addLayout(btn_layout)
if __name__ == '__main__':
app = Qt.QApplication([])
w = Widget()
w.show()
app.exec()