如何控制QGroupBox的大小调整

时间:2017-01-21 07:14:14

标签: python pyqt qgroupbox

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

enter image description here

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_()

1 个答案:

答案 0 :(得分:2)

ekhumoro最简单的一个:

enter image description here

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_()