Search code examples
c++qtqwidgetqtabwidget

How to force a widget to resize together with its parent TabWidget - with code


I looked in every thread and non of it works. some of them discussing about doing it from the Qt Designer (which I already know how to do, but it's not useful because the tabs are added dynamically). some of them discussing about how to do that by code, but still nothing works.

The important code is inside appendTab() :

TabWidgetCSD::TabWidgetCSD(QWidget *parent)
    : QTabWidget(parent)
{
    TabBarCSD* bar = new TabBarCSD();
    setTabBar(bar);

    // create absolute button to the right. it will change the position everytime something happens
    // and it will  will take the last index
    QIcon icon(svgToColorIcon(":/images/plus.svg"));
    openTabBtn = new QPushButton(icon, "", this);
    openTabBtn->setFlat(true);
    openTabBtn->setFixedSize(QSize(29, 29));
    openTabBtn->setIconSize(QSize(25, 25));
    connect(openTabBtn, &QPushButton::clicked, this, [=, this](){
        appendTab();
    });
    appendTab();
}


void TabWidgetCSD::appendTab()
{
    // create page and get it's index
    auto l = new QVBoxLayout();
    auto mainMenuForm = new MainMenuForm;
    l->addWidget(mainMenuForm);
    setLayout(l);
    auto tabIdx = addTab(mainMenuForm, "");


    QIcon icon(svgToColorIcon(":/images/times.svg"));
    QLabel* label = new QLabel;
    label->setText("Main Window");
    label->setAlignment(Qt::AlignCenter);
    label->setFixedWidth(175);
    auto btn = new QPushButton(icon, "");
    btn->setFlat(true);
    btn->connect(btn, &QPushButton::clicked, this, [=, this]() {
        removeTab(tabIdx);
    });
    auto hbox = new QHBoxLayout();
    hbox->setAlignment(Qt::AlignCenter);
    hbox->addWidget(label);
    hbox->addWidget(btn);
    auto wrapper = new QWidget();
    wrapper->setLayout(hbox);
    wrapper->setFixedSize(220, 30);

    tabBar()->setTabButton(tabIdx, QTabBar::LeftSide, wrapper);
}

Solution

  • Your problem is here:

        auto l = new QVBoxLayout();
        auto mainMenuForm = new MainMenuForm;
        l->addWidget(mainMenuForm);
        setLayout(l);
        auto tabIdx = addTab(mainMenuForm, "");
    

    I don't know whether you may want to set layout l on mainMenuForm, but I'm fairly certain you don't want to set it on the calling TabWidgetCSD (which I assume is a QTabWidget), for each added tab. Probably all you want is

        auto tabIdx = addTab(new MainMenuForm, "");
    

    (and if you really need to add a layout on the MainMenuForm, you'll add it in the MainMenuForm c'tor).