11

Assuming I have a QTabWidget that contains 5 sub-tabs. Now I want to show/hide a sub-tab in one of 5 sub-tabs by following code

ui->twListTabs->widget(0)->hide();           // Hide first sub-tab

But this didn’t work for me. Do you have any solutions?

Thanks!

Tan Viet
  • 1,983
  • 6
  • 25
  • 36

2 Answers2

13

You only have the option to use:

void QTabWidget::removeTab(int index)

You need to store the pointer to the QWidget in the tab so that you can later insert it.

You could e.g. do something like:

class TabWidget : public QTabWidget
{
    Q_OBJECT          
    enum tabwidgets {tabwidget1,tabwidget2,...,number_of_tabwidgets};
    QWidget* widgets_[number_of_tabwidgets];
public:
    TabWidget(QWidget* parent = 0) : QWidget(parent)
    {
        for(int i(0); i < number_of_tabwidgets; ++i)
        {
            switch(i)
            {
            case tabwidget1:
                insertTab(i,widgets_[i] = new TabWidget1,QString::number(i));
                ....
            }
        }
    }
};
Alexander Chernin
  • 446
  • 2
  • 8
  • 17
user2672165
  • 2,986
  • 19
  • 27
  • 6
    If you have the tab in the UI Designer of Qt Creator, there's no need for this complexity. Just use `removeTab` and later, to add it back, just use the `findChild` function to pull up the tab (it's still there, managed by the UI object, even after being removed from the tab widget). See comment dated Aug 12, 2011 here: http://www.qtcentre.org/threads/16505-Hiding-a-tab-in-QTabBar-widget?p=200059#post200059 (and it works for me, 6 years later). – Dan Nissenbaum Feb 12 '17 at 12:27
  • @Dan Nissenbaum yes it is a matter of coding style. You see a lot of code around storing pointers to various gui controls, but I've also started to use findChild more. Also lambda callback that is available from C++11 reduces the need to store pointers. – user2672165 Feb 12 '17 at 13:36
  • 1
    @DanNissenbaum : You should put your reply as an answer. Anyway, thank you. – McLan Mar 20 '18 at 13:24
  • 7
    Qt 5.15 introduced a setTabVisible method, see: https://doc.qt.io/qt-5/qtabwidget.html#setTabVisible – Reinder Jun 08 '20 at 08:34
1

To hide I used:

ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabToBeRemoved));

To show I believe you can insert it back with insertTab() to the same position/index.

In Qt 5.15+ you can use setTabVisible().

Adriel Jr
  • 2,451
  • 19
  • 25