Snuh
Snuh

Reputation: 360

Adding a widget to the bottom of a window without resizing other widgets

I have a PyQt application that is mainly a set of buttons. I would to have a QTextEdit window at the bottom that is hidden by default, but the user can toggle off and on. The problem I'm encountering, however, is that when the user turns the TextEdit widget on, the buttons resize. I would like all the buttons to remain the same and the state of the QTextEdit to not visually affect anything. The first image is how I always want the buttons to look, regardless if the TextEdit is toggled on or off. The second is how it looks when I hide the TextEdit and I want it to NOT do this.

My code:

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.central_widget = QWidget(self)
        self.main_layout = QVBoxLayout(self.central_widget)
        for i in range(5):
            btn = QPushButton()
            btn.setText("Button:" + str(i+1))
            btn.clicked.connect(self.toggle_log)
            self.main_layout.addWidget(btn)
        self.central_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.central_widget)
        self.console = QTextEdit()
        self.main_layout.addWidget(self.console)
        self.show()

    def toggle_log(self):
        if self.console.isHidden():
            self.console.show()
        else:
            self.console.hide()

Upvotes: 0

Views: 242

Answers (1)

eyllanesc
eyllanesc

Reputation: 243887

A possible solution is to recalculate the sizes an instant after being shown or hidden:

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.central_widget = QWidget(self)
        self.main_layout = QVBoxLayout(self.central_widget)
        for i in range(5):
            btn = QPushButton()
            btn.setText("Button:" + str(i + 1))
            btn.clicked.connect(self.toggle_log)
            self.main_layout.addWidget(btn)
        self.central_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.central_widget)
        self.console = QTextEdit()
        self.main_layout.addWidget(self.console)
        self.show()

    def toggle_log(self):
        if self.console.isHidden():
            QTimer.singleShot(0, self.resize_show)
            self.console.show()
        else:
            self.central_widget.updateGeometry()
            QTimer.singleShot(0, self.resize_hide)
            self.console.hide()

    def resize_show(self):
        self.resize(self.width(), self.sizeHint().height())

    def resize_hide(self):
        self.resize(self.width(), self.minimumSizeHint().height())

Upvotes: 3

Related Questions