如果您是PySide/PyQt的新手,請參閱文檔中的Layout Management文章,以獲取Qt佈局系統的概述。
對於您的具體示例,您需要一種遞歸移除和刪除佈局(即其所有子部件,間隔項和其他佈局)中的所有對象的方法。還有一種構建和添加新佈局的方法。
這裏有一個簡單的演示:
from PySide import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.changeLayout(QtCore.Qt.Vertical)
self.button = QtGui.QPushButton('Horizontal', self)
self.button.clicked.connect(self.handleButton)
layout.addStretch()
layout.addWidget(self.button)
def handleButton(self):
if self.button.text() == 'Horizontal':
self.changeLayout(QtCore.Qt.Horizontal)
self.button.setText('Vertical')
else:
self.changeLayout(QtCore.Qt.Vertical)
self.button.setText('Horizontal')
def changeLayout(self, direction):
if self.layout().count():
layout = self.layout().takeAt(0)
self.clearLayout(layout)
layout.deleteLater()
if direction == QtCore.Qt.Vertical:
layout = QtGui.QVBoxLayout()
else:
layout = QtGui.QHBoxLayout()
for index in range(3):
layout.addWidget(QtGui.QLineEdit(self))
self.layout().insertLayout(0, layout)
def clearLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 300, 100)
window.show()
sys.exit(app.exec_())
但爲什麼QLineEdit的對象都沒有,當我在我的佈局應用takeAt方法?我刪除除了這個QLineEdit之外的所有東西。 – user3329477
@ user3329477。沒有看到你的代碼是不可能的。 – ekhumoro
'clearLayout'示例非常有幫助! –