Qt有无类似于C#的WrapPanel容器,如果没有用什么容器能实现这样的工能

用Qt编写桌面程序,有多个按钮间隔相同依次排序,当第一行按钮拍到最边时没有空间会自动换到下一样继续,类似与C#的WrapPanel容器。

您好,在Qt中可以使用布局管理器来实现类似于C#的WrapPanel容器的效果。对于您的需求,可以使用QVBoxLayout和QHBoxLayout结合使用来创建一个自动换行的按钮容器。

此处给您一段参考代码,您可以学习一下,并灵活的使用。

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget window;
    QVBoxLayout *mainLayout = new QVBoxLayout(&window);

    // 创建按钮容器
    QWidget *buttonContainer = new QWidget(&window);
    QHBoxLayout *buttonLayout = new QHBoxLayout(buttonContainer);

    // 设置按钮间隔
    buttonLayout->setSpacing(10); 

    // 创建按钮
    for (int i = 1; i <= 10; i++) {
        QPushButton *button = new QPushButton(QString("Button %1").arg(i), buttonContainer);
        buttonLayout->addWidget(button);

        // 当按钮容器宽度不够时,自动换行
        if (buttonLayout->geometry().width() > buttonContainer->geometry().width()) {
            buttonLayout = new QHBoxLayout(buttonContainer);
            buttonLayout->setSpacing(10);
            mainLayout->addWidget(buttonContainer);
        }
    }

    mainLayout->addWidget(buttonContainer);
    window.setLayout(mainLayout);
    window.show();

    return app.exec();
}