Search code examples
c++qtqwidgetqtabwidgetqtabbar

QTabWidget or QTabBar displaying the same QWidget in different tabs using C++


I'm working with a QTabWidget right now displaying just one QWidget with different elements (labels, buttons, ...). Working with Ubuntu and Qt5.5.

QTabWidget *tw;
QString title = "1";
ui->tw->addTab(&tab, title); // tab is my QWidget

I'd like to show the same QWidget in more than one tab with different values. Is there a "clean" for it?

Micha


Solution

  • No, there is not a "clean" way to do that. The QTabWidget uses a stack, so you will need to have separate widgets for each tab. It is said in the documentation :

    Each tab is associated with a different widget (called a page).

    The only way is to instantiate several instances of QWidget and add them to your QTabWidget.

    QTabWidget *tw;
    QString title  = "1";
    QString title2 = "2";
    ui->tw->addTab(&tab, title);   // tab is your QWidget
    ui->tw->addTab(&tab2, title2); // tab2 is another QWidget
    

    If you want to use a QTabBar, just put your widget within it (using a QVBoxLayout for example). Then connect to the QTabBar's currentChanged signal to change your widget according to your needs.