QT 布局演示例子

发布于:2024-07-11 ⋅ 阅读:(16) ⋅ 点赞:(0)
  • 效果

  • 源码
#include <QApplication>
#include <QWidget>
#include <QSplitter>
#include <QVBoxLayout>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget mainWidget;
    mainWidget.setWindowTitle("QtLayoutExample");
    mainWidget.showMaximized(); // 默认最大化

    QVBoxLayout *mainLayout = new QVBoxLayout(&mainWidget);

    QSplitter *splitterHorizontal = new QSplitter(Qt::Horizontal);
    QSplitter *splitterVertical = new QSplitter(Qt::Vertical);

    QWidget *leftWidget = new QWidget();
    leftWidget->setStyleSheet("background-color: lightblue;");
    QVBoxLayout *leftLayout = new QVBoxLayout(leftWidget);
    QLabel *leftLabel = new QLabel("Left Widget");
    leftLayout->addWidget(leftLabel);

    QWidget *rightWidget = new QWidget();

    QWidget *rightWidgetBottom = new QWidget();
    rightWidgetBottom->setStyleSheet("background-color: lightgreen;");
    QVBoxLayout *bottomLayout = new QVBoxLayout(rightWidgetBottom);
    QLabel *bottomLabel = new QLabel("Bottom Widget");
    bottomLayout->addWidget(bottomLabel);

    QWidget *rightWidgetTop = new QWidget();
    rightWidgetTop->setStyleSheet("background-color: lightyellow;");
    QVBoxLayout *topLayout = new QVBoxLayout(rightWidgetTop);
    QLabel *topLabel = new QLabel("Top Widget");
    topLayout->addWidget(topLabel);

    QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);

    splitterVertical->addWidget(rightWidgetTop);
    splitterVertical->addWidget(rightWidgetBottom);

    rightLayout->addWidget(splitterVertical);

    splitterHorizontal->addWidget(leftWidget);
    splitterHorizontal->addWidget(rightWidget);

    mainLayout->addWidget(splitterHorizontal);

    mainWidget.setLayout(mainLayout);
    mainWidget.show();

    return app.exec();
}