4
votes

I have a QTabWidget with dynamically added and removed tabs. I have also a QToolButton set as a corner widget in order to handle add events on its clicked() signal.

While adding works perfectly fine removing all tabs from the widget causes the button to disappear. I have tried using stylesheets to create a invisible first tab of width 0, but this approach failed me. Probably because I have setTabsClosable(true) on all tabs which makes space for the close button.

I also thought that button is disappearing when QTabBar collapses its hight to 0 when there is no tabs. I tried to tabBar()->setMinimumHeight(30); but this workaround also didn't work. Any ideas?

Here my code sample reproducing the problem:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QToolButton"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->tabWidget->setTabsClosable(true);
    ui->tabWidget->tabBar()->setMinimumHeight(30);

    QToolButton *btn = new QToolButton(ui->tabWidget);
    btn->setText("Add new");
    btn->setCursor(Qt::ArrowCursor);
    btn->setAutoRaise(true);
    ui->tabWidget->setCornerWidget(btn, Qt::TopLeftCorner);

    qDebug() << ui->tabWidget->cornerWidget(Qt::TopLeftCorner);  

    connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));

}

MainWindow::~MainWindow()
{
    delete ui;
}

//SLOT
void MainWindow::closeTab(int index)
{
    ui->tabWidget->removeTab(index);
    if(ui->tabWidget->count() == 0)
        qDebug() << ui->tabWidget->cornerWidget(Qt::TopLeftCorner);
}
1
Did you tried to test ui->tabWidget->cornerWidget() after deleting the last tab to see if it has been removed (== 0) ? - Sylvain V
Yes, qDebug() run when ui->tabWidget->count() == 0 shows it is still there. Updated code with this test. - Mateusz Andrzejewski

1 Answers

5
votes

I've got this solved. You need to fix the minimum height for both the QToolButton and the QTabBar.

So far I've got this code working in python:

def initialise()
    # Initialise your Tab Widget however you need
    self.tabCloseRequested.connect(self.removeTab)

def removeTab(self,index):
    h = self.cornerWidget().height()

    self.removeTab(index)
    self.update()
    if self.count() == 0:
        self.cornerWidget().setMinimumHeight(h)
        self.setMinimumHeight(h)