Размещение элементов снизу вверх в PyQt6

Как в PyQt6 размешать кнопки снизу вверх так, чтобы они были сбоку? пример


Ответы (1 шт):

Автор решения: FindMeTomorrow

Если вы хотите разместить кнопки вертикально снизу вверх, то один из вариантов - использовать QVBoxLayout и установить направление с помощью setDirection(QBoxLayout.Direction.BottomToTop).

Чтобы разместить блок с кнопками слева, можно объявить внешний контейнер с QHBoxLayout и первым поместить в него виджет с кнопками.

Пример:

from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel, QPushButton,
                             QBoxLayout, QVBoxLayout, QHBoxLayout)


class ButtonContainer(QWidget):
    def __init__(self, parent: QWidget | None = None) -> None:
        super().__init__(parent)
        self.main_layout = QVBoxLayout(self)
        self.buttons: list[QPushButton] = []

        self.setup_ui()

    def setup_ui(self):
        self.setLayout(self.main_layout)
        self.main_layout.setDirection(QBoxLayout.Direction.BottomToTop)

        for i in range(5):
            button = QPushButton(str(i), self)
            self.buttons.append(button)
            self.main_layout.addWidget(button)


class MainWindow(QMainWindow):
    def __init__(self) -> None:
        super().__init__()
        self.main_layout = QHBoxLayout(self)
        self.main_widget = QWidget(self)
        self.button_container = ButtonContainer(self.main_widget)
        self.label = QLabel("Другие виджеты", self.main_widget)

        self.setup_ui()

    def setup_ui(self):
        self.setCentralWidget(self.main_widget)
        self.main_widget.setLayout(self.main_layout)

        self.main_layout.addWidget(self.button_container)
        self.main_layout.addWidget(self.label)


if __name__ == '__main__':
    app = QApplication([])
    w = MainWindow()
    w.show()

    app.exec()

результат работы программы

→ Ссылка