2

I am creating a QTabWidget that has a number of tabs and each tab contains a different number of push buttons. Because some of these tabs may include many push buttons, I would like to make each tab scrollable.

I have an implementation that sort of works except no matter what I try I can't get the darn QTabWidget to be of a particular vertical size - it always wants to size itself based on the maximum height used by one of its pages. I've tried changing size policies, layout strategies and nothing works.

Here is exact widget structure I am using:

QFrame
    QSplitter
        QTabWidget
        QFrame

I populate the QTabWidget with QWidget instances that serve as pages. These instances are wrapped around with a QScrollArea and use a QGridLayout so that I can populate the tab with push buttons in a grid.

Here is the actual code that populates the tab widget:

for (const std::string &tabName : tabs) {
    // Grid layout for each tab
    QGridLayout *gridLayout = new QGridLayout();

    // The tab widget itself
    QWidget *page = new QWidget(tabWidget);
    page->setLayout(gridLayout);

    // Wrap tab with a scroll area so that it's scrollable when the tab widget
    // is resized to be smaller than the page size
    QScrollArea *scrollArea = new QScrollArea(tabWidget);
    scrollArea->setWidgetResizable(true);
    scrollArea->setWidget(page);

    tabWidget->addTab(scrollArea, tabName.c_str());

    // Populate tab with push buttons
    const std::vector<std::string> &buttons = GetButtons(tabName);
    for (const std::string &buttonName : buttons) {
        QPushButton *button = new QPushButton(buttonName.c_str());
        button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
        QSize buttonSize(130, 20);
        button->setFixedSize(buttonSize); // <=== this does work
        int row = i / numColumns;
        int col = i % numColumns;
        gridLayout->addWidget(button, row, col, Qt::AlignLeft | Qt::AlignTop);
    }
}

// This does not work
const int fixedVerticalSize = 120;
tabWidget->resize(tabWidget->size().width(), fixedVerticalSize); 

BTW, I am using Qt 5.0.2 on Mac OS X 10.8.2.

4

0 回答 0