简体   繁体   中英

How to make widgets automatically stretch to the parent widget's size in Qt Designer

I need to add a TabWidget control to the MainWindow and place TableWidget in every tab it has. The problem is that I need to make them automatically stretch to the parent widget's size ( TabWidget to the window's size, TableWidget 's to the TabWidget 's size).

What is the easiest way to achieve it via Qt Designer?

You should use Qt layouts.

In designer you have to select the widget you want to have its children laid out properly, then choose Form -> Lay Out Vertically/Horizontally/... shortcuts: Ctrl+1...6

Below is an example program that will create a view as you needed. Logic is Mainwindow-> Central Widget-> Add Vertical Layout-> Add Tab Widget
->Add Tab 1->Add V Box Layout -> Add Table 1 (5 X 5)
->Add Tab 2->Add V Box Layout -> Add Table 1 (5 X 5)

Code comment will explain in detail.

void MainWindow::fnInit()
{
    //Layout to the MainWindow
    QVBoxLayout *vLayoutMain;
    QTabWidget *Tab;
    QWidget *Widget1;
    //Layout to the Tab1
    QVBoxLayout *vLayoutTab1;
    QTableWidget *Table1;
    QWidget *Widget2;
    //Layout to the Tab2
    QVBoxLayout *vLayoutTab2;
    QTableWidget *Table2;

    //Set Vertical Box Layout to the main Window (central widget)
    vLayoutMain = new QVBoxLayout(this->centralWidget());
    Tab = new QTabWidget(this->centralWidget());

    Widget1 = new QWidget();
    //Set the Vertical Box Layout to the Widget 1 (holds the tab1)
    vLayoutTab1 = new QVBoxLayout(Widget1);
    Table1 = new QTableWidget(5,5,Widget1);
    vLayoutTab1->addWidget(Table1);
    Tab->addTab(Widget1, QString("Tab 1"));

    Widget2 = new QWidget();
    //Set the Vertical Box Layout to the Widget 2 (holds the tab2)
    vLayoutTab2 = new QVBoxLayout(Widget2);
    Table2 = new QTableWidget(5,5,Widget2);
    vLayoutTab2->addWidget(Table2);

    Tab->addTab(Widget2, QString("Tab 2"));

    //Adding the Tab widget to the main layout
    vLayoutMain->addWidget(Tab);
    Tab->setCurrentIndex(0);
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM