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



相关推荐
后台开发者Ethan30 分钟前
Python需要了解的一些知识
开发语言·人工智能·python
常利兵1 小时前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
幼稚园的山代王1 小时前
Kotlin-基础语法练习一
android·开发语言·kotlin
重生成为编程大王2 小时前
Java ConcurrentHashMap 深度解析
java·开发语言
tanyongxi662 小时前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
遗憾皆是温柔2 小时前
24. 什么是不可变对象,好处是什么
java·开发语言·面试·学习方法
wearegogog1232 小时前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互
Fine姐3 小时前
The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
开发语言·网络·php·硬件架构
HAPPY酷3 小时前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf
liulilittle3 小时前
BFS寻路算法解析与实现
开发语言·c++·算法·宽度优先·寻路算法·寻路