qt布局设置(1,2,4,6,8,9,12,16等布局)

.h

#ifndef VIDEOSPACE_H
#define VIDEOSPACE_H

#include <QWidget>
#include <QComboBox>
#include <QGridLayout>
#include <QVBoxLayout>
#include <QFrame>
QT_BEGIN_NAMESPACE
namespace Ui { class VideoSpace; }
QT_END_NAMESPACE

class VideoSpace : public QWidget
{
    Q_OBJECT

public:
    VideoSpace(QWidget *parent = nullptr);
    ~VideoSpace();
private slots:
    void updateLayout(const QString &text);
private:
    Ui::VideoSpace *ui;
    QGridLayout *gridLayout;
};

#endif // VIDEOSPACE_H

.cpp

#include "videospace.h"
#include "ui_videospace.h"
#include <QPushButton>
#include <QLabel>
#include <QtMath>
VideoSpace::VideoSpace(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::VideoSpace)
{
    ui->setupUi(this);
    // 创建下拉框
    QComboBox *comboBox = new QComboBox(this);
    comboBox->addItems({"1", "2", "4", "6", "8", "9", "12", "16"});

    // 创建布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(comboBox);

    // 添加网格布局
    gridLayout = new QGridLayout();
    mainLayout->addLayout(gridLayout);

    // 连接信号和槽
    connect(comboBox, &QComboBox::currentTextChanged, this, &VideoSpace::updateLayout);

    // 初始化布局
    updateLayout(comboBox->currentText());

}

VideoSpace::~VideoSpace()
{
    delete ui;
}

void VideoSpace::updateLayout(const QString &text)
{
    // 清空当前布局
    QLayoutItem *item;
    while ((item = gridLayout->takeAt(0))) {
        delete item->widget();
        delete item;
    }

    int count = text.toInt();
    int rows = static_cast<int>(qSqrt(count));
    int cols = (count + rows - 1) / rows; // 向上取整

    // 创建分屏
    for (int i = 0; i < count; ++i) {
        QFrame *frame = new QFrame();
        frame->setFrameShape(QFrame::Box);
        frame->setLineWidth(2);
        frame->setStyleSheet("background-color: lightgray;");
        gridLayout->addWidget(frame, i / cols, i % cols);
    }
}


在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值