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

.h

cpp 复制代码
#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

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);
    }
}



相关推荐
森G1 小时前
29、QStringListModel 和 QListView---------Model/View模型视图
c++·qt
0xDevNull7 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
小小亮017 小时前
Next.js基础
开发语言·前端·javascript
ALex_zry7 小时前
C++网络编程心跳机制与连接保活:长连接稳定性保障
开发语言·网络·c++
Amumu121388 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
Sgf2278 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
好大哥呀9 小时前
C++ Web 编程
开发语言·前端·c++
ID_180079054739 小时前
小红书笔记评论 API,Python 调用示例与完整 JSON 返回参考
java·开发语言
南境十里·墨染春水10 小时前
C++ 笔记 友元(面向对象)
开发语言·c++·笔记
TT_441910 小时前
python程序实现图片截图溯源功能
开发语言·python