pyside show / hide layouts

2019-06-16 10:10发布

I'm trying to display one of two layouts depending on whether a checkbox is checked or not.

Only using widgets I can do the following which works fine: (each widget in this example is a QLineEdit)

myCheckbox.stateChanged.connect(switchControls)

def switchControls (self, state):
    if state == 2:
        self.widget1.show()
        self.widget2.hide()
    else:
        self.widget1.hide()
        self.widget2.show()

However, since I want to add a descriptive label to each QLineEdit, I need to combine a QLineEdit+QLabel in a layout or container of some kind. I have been trying the addlayout / removeLayout / removeItem to do the above on layouts instead of widgets, but can't get it to work. The program crashed on my last try.

What is the easiest way to switch between two layouts? It doesn't have to use a checkbox but I'd prefer that.

1条回答
干净又极端
2楼-- · 2019-06-16 10:58

Put the layouts into separate widgets. Now you're "only using widgets".

Here's an example:

from PySide.QtCore import *
from PySide.QtGui import *

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.layout=QVBoxLayout()
        self.setLayout(self.layout)


        self.checkbox=QCheckBox("Layouts")
        self.layout.addWidget(self.checkbox)


        self.widget1=QWidget()
        self.layout.addWidget(self.widget1)

        self.layout1=QVBoxLayout()
        self.widget1.setLayout(self.layout1)

        self.layout1.addWidget(QLabel("First layout"))

        self.layout1.addWidget(QTextEdit())


        self.widget2=QWidget()
        self.layout.addWidget(self.widget2)

        self.layout2=QHBoxLayout()
        self.widget2.setLayout(self.layout2)

        self.layout2.addWidget(QTextEdit("Second layout"))

        self.layout2.addWidget(QTextEdit())


        self.checkbox.toggled.connect(self.checkbox_toggled)
        self.checkbox.toggle()

        self.show()

    def checkbox_toggled(self, state):
        self.widget1.setVisible(state)
        self.widget2.setVisible(not state)

app=QApplication([])
mw=MainWindow()
app.exec_()

Run it to see how it works.

查看更多
登录 后发表回答