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?
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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With