Pyside改变布局

时间:2013-01-10 22:22:09

标签: qt pyside

我有一个界面,屏幕顶部有4个按钮,下面我有QFrame。我想根据按下的按钮更改QFrame中的布局。例如,如果按下Button_1,则显示TextEdit Widget,如果按下Button_2则显示ListViewWidget。

有没有人知道如何做到这一点? 非常感谢!

2 个答案:

答案 0 :(得分:6)

使用QStackedLayout存储您的小部件。然后您可以更改为setCurrentIndex的那个。或者,您可以使用QStackedWidget代替QFrame

一个简单的例子:

import sys
from PySide import QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.textEdit = QtGui.QTextEdit('Text Edit')
        self.listWidget = QtGui.QListWidget()
        self.listWidget.addItem('List Widget')
        self.label = QtGui.QLabel('Label')

        self.stackedLayout = QtGui.QStackedLayout()
        self.stackedLayout.addWidget(self.textEdit)
        self.stackedLayout.addWidget(self.listWidget)
        self.stackedLayout.addWidget(self.label)

        self.frame = QtGui.QFrame()
        self.frame.setLayout(self.stackedLayout)

        self.button1 = QtGui.QPushButton('Text Edit')
        self.button1.clicked.connect(lambda: self.stackedLayout.setCurrentIndex(0))
        self.button2 = QtGui.QPushButton('List Widget')
        self.button2.clicked.connect(lambda: self.stackedLayout.setCurrentIndex(1))
        self.button3 = QtGui.QPushButton('Label')
        self.button3.clicked.connect(lambda: self.stackedLayout.setCurrentIndex(2))

        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addWidget(self.button1)
        buttonLayout.addWidget(self.button2)
        buttonLayout.addWidget(self.button3)

        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(buttonLayout)
        layout.addWidget(self.frame)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())

答案 1 :(得分:2)

像...一样的东西。

myframe.layout().removeWidget(mywidget)
mywidget = QTextEdit()
myframe.layout().addWidget(myWidget)