如何控制QGroupBox调整大小

How to control QGroupBox resizing

下面的代码创建一个对话框,GroupBox() 调整大小与对话框同步。这是 GroupBox 的默认调整大小策略。如何更改此策略,使 GroupBox 占用尽可能少的 space(区域)并且永远不会垂直扩展。如何实现?

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

panel=QtGui.QDialog()
panel.setLayout(QtGui.QVBoxLayout())

groupbox = QtGui.QGroupBox('Group Box')
groupbox.setLayout(QtGui.QVBoxLayout())
panel.layout().addWidget(groupbox)

for i in range(3):
    row = QtGui.QHBoxLayout()
    row.addWidget(QtGui.QLabel('Label'))
    row.addWidget(QtGui.QLineEdit())
    row.addWidget(QtGui.QPushButton('Push Button'))
    groupbox.layout().addLayout(row)

panel.layout().addWidget(QtGui.QPushButton('Confirm'))

panel.show()
app.exec_()

ekhumoro 最简单的一个:

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

panel=QtGui.QDialog()
panel.setLayout(QtGui.QVBoxLayout())

groupbox = QtGui.QGroupBox('Group Box')
groupbox.setLayout(QtGui.QVBoxLayout())
panel.layout().addWidget(groupbox)
panel.layout().addStretch()

for i in range(3):
    row = QtGui.QHBoxLayout()
    row.addWidget(QtGui.QLabel('Label'))
    row.addWidget(QtGui.QLineEdit())
    row.addWidget(QtGui.QPushButton('Push Button'))
    groupbox.layout().addLayout(row)

panel.layout().addWidget(QtGui.QPushButton('Confirm'))

panel.show()
app.exec_()

第二种方法在我们将 .addWidget 替换为 .addItem 后同样有效:

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

panel=QtGui.QDialog()
panel.setLayout(QtGui.QVBoxLayout())

groupbox = QtGui.QGroupBox('Group Box')
groupbox.setLayout(QtGui.QVBoxLayout())
panel.layout().addWidget(groupbox)
panel.layout().addItem(QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding))
for i in range(3):
    row = QtGui.QHBoxLayout()
    row.addWidget(QtGui.QLabel('Label'))
    row.addWidget(QtGui.QLineEdit())
    row.addWidget(QtGui.QPushButton('Push Button'))
    groupbox.layout().addLayout(row)

panel.layout().addWidget(QtGui.QPushButton('Confirm'))

panel.show()
app.exec_()