且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Qt动态创建布局并向布局添加小部件

更新时间:2023-11-14 16:50:22

您的过程正确.有一些错别字,例如,您为frame3设置了两次布局.那可能是你的问题.崩溃并非总是可以重现.除此以外,我认为您没有其他问题.以下是一个自包含的示例.它还可以按值保留所有实例,避免过早地通过指针对额外的取消引用进行了悲观的预测.

Your procedure is correct. There are some typos, for example, you're setting the layout twice for frame3. That may be your problem. Crashes aren't always reproducible. I don't think you have any other problems than that. Below is a self contained example. It also keeps all the instances by value, avoiding the premature pessimization of an extra dereference via a pointer.

// https://github.com/KubaO/***n/tree/master/questions/dynamic-widget-10790454
#include <cmath>
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif
#include <array>

// Interface

class ClockView : public QLabel
{
public:
    explicit ClockView(QWidget* parent = nullptr) : QLabel(parent)
    {
        static int ctr = 0;
        setText(QString::number(ctr++));
    }
};

class MainWindow : public QMainWindow
{
public:
    explicit MainWindow(QWidget *parent = nullptr);
    void populateViewGrid();

private:
    static constexpr int N = 10;

    QWidget central{this};
    QGridLayout centralLayout{&central};
    std::array<QFrame, N> frames;

    std::array<ClockView, N> clockViews;
    std::array<QVBoxLayout, N> layouts;
};

// Implementation

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setCentralWidget(&central);

    const int n = ceil(sqrt(N));
    for (int i = 0; i < N; ++ i) {
        frames[i].setFrameShape(QFrame::StyledPanel);
        centralLayout.addWidget(&frames[i], i/n, i%n, 1, 1);
    }

    populateViewGrid();
}

void MainWindow::populateViewGrid()
{
    for (int i = 0; i < N; ++ i) {
        layouts[i].addWidget(&clockViews[i]);
        frames[i].setLayout(&layouts[i]);
    }
}

int main(int argc, char** argv)
{
    QApplication app{argc, argv};
    MainWindow w;
    w.show();
    return app.exec();
}

还有qmake项目文件.

And the qmake project file.

greaterThan(QT_MAJOR_VERSION, 4) {
    QT = widgets 
    CONFIG += c++11
} else {
    QT = gui 
    unix:QMAKE_CXXFLAGS += -std=c++11
    macx {
        QMAKE_CXXFLAGS += -stdlib=libc++
        QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.7
    }
}
TARGET = dynamic-widget-10790454
TEMPLATE = app
SOURCES += main.cpp