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



相关推荐
ZTLJQ38 分钟前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
2401_891482171 小时前
多平台UI框架C++开发
开发语言·c++·算法
anzhxu1 小时前
QT数据库(三):QSqlQuery使用
数据库·qt·oracle
88号技师1 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751281 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
m0_726965982 小时前
面面面,面面(1)
java·开发语言
2401_831920742 小时前
分布式系统安全通信
开发语言·c++·算法
~无忧花开~2 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架
阿贵---3 小时前
C++中的RAII技术深入
开发语言·c++·算法
Traced back3 小时前
怎么用 Modbus 让两个设备互相通信**,包含硬件接线、协议原理、读写步骤,以及 C# 实操示例。
开发语言·c#