c++qtqtabwidget

Is there a way to make QTabWidgets auto-hide the tab bar if only one tab is visible (but there are multiple tabs)?


I have a QTabWidget instance called tabWidget, and it has two QTableWidget children.

I've called setTabBarAutoHide(true) on the QTabWidget, and I've also called setTabVisible with false as a parameter for the second tab.

I expected setTabBarAutoHide(true) to mean that the tab bar will not be displayed since there is only one visible tab. However, this is not the case - there's only one visible tab and the bar is not hidden.

If I never add the second tab, the behavior is as expected - the tab bar stays hidden.

Here is a rough idea of what my code looks like:

QTabWidget* tabWidget = new QTabWidget();
tabWidget->setTabBarAutoHide(true);

QTableWidget* firstTab = new QTableWidget();
tabWidget->addTab(firstTab, "First Tab");

QTableWidget* secondTab = new QTableWidget();
tabWidget->addTab(secondTab, "Second Tab");
tabWidget->setTabVisible(1, false);

Is there a "nice" way to auto-hide the tab bar if only one tab is visible (but multiple tabs exist)? If not, what is the most idiomatic way to get this functionality?


Solution

  • In Qt, setTabBarAutoHide(true) is indeed supposed to automatically hide the tab bar when there's only one tab visible. However, it seems there might be a conflict with setting a tab to be invisible using setTabVisible(false).

    To achieve the behavior you want, you can use a workaround. Instead of using setTabVisible(false) to hide the second tab, you can remove it from the QTabWidget. Then, when you want to show it again, you can add it back. This way, the setTabBarAutoHide(true) should work as expected.

    like this:

    #include <QApplication>
    #include <QTabWidget>
    #include <QTableWidget>
    
    int main(int argc, char *argv[]) {
        QApplication a(argc, argv);
    
        // Create the QTabWidget
        QTabWidget* tabWidget = new QTabWidget();
        tabWidget->setTabBarAutoHide(true);
    
        // Create the first tab and add it to the tab widget
        QTableWidget* firstTab = new QTableWidget();
        tabWidget->addTab(firstTab, "First Tab");
    
        // Create the second tab and add it to the tab widget
        QTableWidget* secondTab = new QTableWidget();
        tabWidget->addTab(secondTab, "Second Tab");
    
        // Remove the second tab from the tab widget
        tabWidget->removeTab(1);
    
        // Show the tab widget
        tabWidget->show();
    
        return a.exec();
    }