Qt网格布局无法在滚动区

时间:2015-10-16 05:35:52

标签: c++ qt

我有一个网格布局,里面有一堆QPushButtons和我自己的QToolButtons。我的对话框正在显示我的口味,除非我碰巧有太多的按钮导致网格扩展超出屏幕尺寸。所以我想添加一个滚动条。

我已经阅读了一堆关于滚动条和QtGridLayout的问题/解决方案但是在实现了这个已接受的解决方案之后,例如qdialog with scrollarea and gridlayout 所有我的按钮(其大小应该固定 - 为清晰起见,下面省略相应的代码)缩小到一个愚蠢的大小。此外,当我调整对话框的大小时,滚动区域会相应调整大小,但其中的网格不会。我错过了什么?

注意:我已经尝试了各种方法来修复各种尺寸,基本上一切都没有滚动区域,但是只要我把东西放在滚动区域,网格单元就会自动且无意义地调整大小... < / p>

void createDatabaseWindow()
{
    _database_widget = new QDialog;
    QVBoxLayout* layout(new QVBoxLayout);
    _database_layout = new QGridLayout;

    QLabel* text(new QLabel("some text"));
    layout->addWidget(text);

    QVBoxLayout* vlayout(new QVBoxLayout);
    _new_user_button = new QPushButton("New User");
    vlayout->addWidget(_new_user_button);
    QPushButton* cancel_button(SM_NEW QPushButton("Cancel"));
    vlayout->addWidget(cancel_button);
    _database_layout->addLayout(vlayout, 0, 0);

    std::vector<Result> database = getWholeDatabase();
    for (int i = 0; i < database.size(); i++){
        myQToolButton* button(new myQToolButton(database[i]));
        _database_layout->addWidget(button, (i + 1) / N_ROWS_DATABASE, (i + 1) % N_ROWS_DATABASE);
    }

    // the following comes from an accepted solution, but doesn't work for me...

    //Create a widget and set its layout as your new layout created above
    QWidget *viewport = new QWidget;
    viewport->setLayout(_database_layout);

    //Add the viewport to the scroll area
    QScrollArea *scrollArea = new QScrollArea;
    scrollArea->setWidget(viewport);

    //Add the scroll area to your main window's layout
    layout->addWidget(scrollArea);

    _database_widget->setLayout(layout);


}

1 个答案:

答案 0 :(得分:1)

知道了! 问题是网格布局内容的动态变化。修复一切的神奇之处在于:

_database_layout->setSizeConstraint(QLayout::SetMinAndMaxSize);