CTZStef
CTZStef

Reputation: 1715

Change the widget in a QTabWidget

I can't find the way to replace the QWidget of a specific tab in a QTabWidget, at runtime. I can use addTab then setCurrentWidget, but what if I want to set a QWidget at tab index 1 only, without adding a new tab?

Upvotes: 4

Views: 5970

Answers (2)

This utility function does it:

void replaceTab(QTabWidget * tabs, int index,
                QWidget * replacement, const QString & label = QString())
{
  Q_ASSERT(tabs && tabs->count() > index)
  tabs->removeTab(index);
  if (replacement) tabs->insertTab(index, replacement, label);
}

Upvotes: 1

Matthew
Matthew

Reputation: 2829

One method is to use a parent QWidget as the main QWidget in the tab and change out its child whenever you want to change the tab contents.

Technically you're not changing the QWidget of the tab itself just the first child of the main QWidget in the tab.

For example:

QTabWidget* myTabWidget = new QTabWidget();
QWidget* tab1 = new QWidget();
QWidget* tab1Contents = new QWidget( tab1 );

// [1] Setup the first tab.
myTabWidget.addTab( tab1, "1st Tab" );

// [3] If you now want to remove the original contents 
// and replace with something new.
delete tab1Contents;
QWidget* tab1NewContents = new QWidget( tab1 );

Of course you can add layouts to tab1, tab1Contents, and tab1NewContents ensure your tab contents look nice!

Upvotes: 6

Related Questions