Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyside show / hide layouts

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.

like image 228
user985366 Avatar asked Aug 06 '12 09:08

user985366


People also ask

How do I hide a layout in Qt?

A layout can not be hidden since they are not widgets and does not have a setVisible() function. You have to create a widget that you can hide, that contains the layout and the other widgets that should be hidden, then you hide the widget instead of the layout.

What is layout in PyQt?

In PyQt, layout managers are classes that provide the required functionality to automatically manage the size, position, and resizing behavior of the widgets in the layout. With layout managers, you can automatically arrange child widgets within any parent, or container, widget.


1 Answers

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.

like image 101
Oleh Prypin Avatar answered Nov 06 '22 08:11

Oleh Prypin