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



相关推荐
神秘的t几秒前
javaEE初阶————多线程进阶(2)
java·开发语言
算法工程师y4 分钟前
MATLAB并行计算加速,用 parfor 和 spmd 榨干多核CPU性能
开发语言·matlab
bug总结6 分钟前
map() 方法介绍(JavaScript 数组方法)
开发语言·前端·javascript
轩源源7 分钟前
封装哈希表实现unordered_map和unordered_set
开发语言·数据结构·c++·算法·哈希算法·散列表
白羊不吃白菜13 分钟前
PAT乙级(1091 N-自守数)C语言解析
c语言·开发语言
我的运维人生37 分钟前
从零开始:使用 Python 实现机器学习的基础与实践
开发语言·python·机器学习
2301_789169541 小时前
JSON.parse(JSON.stringify())深拷贝不会复制函数
开发语言·前端·javascript
恋恋风辰1 小时前
QT系列教程(17) MVC结构之Model模型介绍
开发语言·qt·mvc
熊峰峰1 小时前
数据结构第八节:红黑树(初阶)
开发语言·数据结构·c++·算法
cskywit1 小时前
OpenManus介绍及本地部署体验
开发语言·php