⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

[Solved] QTabWidget:setTabBar() -- really undefined behavior?

  • I would like to completely repopulate a QTabWidget with a different group of tabs, quickly and simply.

    I cleverly thought, aha! I could maintain two different QTabBars, each populated with a group of widgets. Then use QTabWidget::setTabBar() to change from one group of tabs to the other.

    Alas I see "the doc for setTabBar()":http://qt-project.org/doc/qt-5/qtabwidget.html#setTabBar says "Note that this must be called before any tabs have been added, or the behavior is undefined."

    Does this really mean one cannot swap loaded tab bars in a tab widget? Could someone familiar with the actual code tell me what will go wrong? Thank you!

  • Moderators

    Best way is to try it yourself, and see what happens. When the devs say "it's undefined" it usually means "untested, might crash", and it always does mean "if it works, great. If it doesn't: well, you have been warned".

    I'll hint at another solution: why not swap the whole QTabWidget, instead of swapping only the tabs?

  • Thanks! I guess I will take the time to write a test case. I thought of swapping the QTabWidget itself, but that's awkward because it is one side of a QSplitter, and QSplitter doesn't seem to offer any method for removing a widget.

    I'll report here on what happens!

  • Lifetime Qt Champion


    Then QStackedWidget to the rescue, you only switch the current tab widget and don't have to fiddle with QSplitter

  • OK, what happens is ... I realize my mistake! Because QTabBar only manages the tabs, not the related widgets. So it would do me no good to swap populated tab bars, that would only change the names on the tabs and perhaps their order.

    QTabWidget manages the relationship between each tab and an associated widget, displaying the latter when the former is clicked. I can well imagine that these relationships could be scrambled in "undefined" ways if I changed the tab bar after widgets were added.

    I will look into QStackedWidget and see if it fits into my app. Thanks for your help.

Log in to reply