Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the widget in a QTabWidget

Tags:

qt

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?

like image 478
CTZStef Avatar asked Oct 21 '25 07:10

CTZStef


2 Answers

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!

like image 145
Matthew Avatar answered Oct 24 '25 05:10

Matthew


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);
}
like image 38
Kuba hasn't forgotten Monica Avatar answered Oct 24 '25 07:10

Kuba hasn't forgotten Monica