PySide6 GUI 编程(17):QVBoxLayout / QHBoxLayout 的简单用法

2024-07-29 21:47:33 浏览数 (1)

QVBoxLayout的用法

代码语言:python代码运行次数:0复制
class VerticallyLayout(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Vertically Layout')
        v_layout = QVBoxLayout()
        v_layout.addWidget(ColorWidget(QColor('red')))
        v_layout.addWidget(ColorWidget(QColor('blue')))
        v_layout.addWidget(ColorWidget(QColor('green')))

        container = QWidget()
        container.setLayout(v_layout)
        self.setCentralWidget(container)

QHBoxLayout的用法

代码语言:python代码运行次数:0复制
class HorizontallyLayout(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Horizontally Layout')
        h_layout = QHBoxLayout()
        h_layout.addWidget(ColorWidget(QColor('red')))
        h_layout.addWidget(ColorWidget(QColor('blue')))
        h_layout.addWidget(ColorWidget(QColor('green')))

        container = QWidget()
        container.setLayout(h_layout)
        self.setCentralWidget(container)

完整示例代码

代码语言:python代码运行次数:0复制
from PySide6.QtGui import QColor, QPalette
from PySide6.QtWidgets import QApplication, QHBoxLayout, QMainWindow, QVBoxLayout, QWidget


class ColorWidget(QWidget):
    def __init__(self, color: QColor):
        super().__init__()
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(QPalette.ColorGroup.Normal, QPalette.ColorRole.Window, color)
        self.setPalette(palette)


class VerticallyLayout(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Vertically Layout')
        v_layout = QVBoxLayout()
        v_layout.addWidget(ColorWidget(QColor('red')))
        v_layout.addWidget(ColorWidget(QColor('blue')))
        v_layout.addWidget(ColorWidget(QColor('green')))

        container = QWidget()
        container.setLayout(v_layout)
        self.setCentralWidget(container)


class HorizontallyLayout(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Horizontally Layout')
        h_layout = QHBoxLayout()
        h_layout.addWidget(ColorWidget(QColor('red')))
        h_layout.addWidget(ColorWidget(QColor('blue')))
        h_layout.addWidget(ColorWidget(QColor('green')))

        container = QWidget()
        container.setLayout(h_layout)
        self.setCentralWidget(container)


if __name__ == '__main__':
    app = QApplication()
    window = QWidget()
    layout = QHBoxLayout()
    layout.addWidget(VerticallyLayout())
    layout.addWidget(HorizontallyLayout())
    window.setLayout(layout)
    window.show()
    app.exec()

运行效果

运行效果运行效果

0 人点赞