amir alizadeh
amir alizadeh

Reputation: 28

Changing the content of a QTabWidget's widget, knowing only the tab index

How do I change the QWidget inside a tab of a QTabWidget, knowing only the tab index?

void MainWindow::on_toolButton_2_clicked()
{
    TextItem myitem = new TextItem;//is a class TextItem : public QWidget
    int tabindex = 2;
    ui->tabwidget1->//i don't have a idea to change widget of a Tab by tab index
}

Upvotes: 0

Views: 1540

Answers (1)

gpalex
gpalex

Reputation: 852

It's hard to say what solution would best suit your problem since you don't explain much of it.

A first approach would be to wrap the content of each tab inside a container QWidget: when you want to change the content of one tab, you just have to change the content of the container QWidget.

Another approach would be to delete the tab with the old content and create a new one with the new content.


EDIT: Here is a quick implementation of the first approach I mentioned above:

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    void buildTabWidget();

private slots:
    void changeTabContent() const;

private:
    QTabWidget* tab_widget;
};

#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"

#include <QLabel>
#include <QLayout>
#include <QPushButton>
#include <QTabWidget>

void MainWindow::buildTabWidget()
{
    // The container will hold the content that can be changed
    QWidget *container = new QWidget;

    tab_widget = new QTabWidget(this);
    tab_widget->addTab(container, "tab");

    // The initial content of the container is a blue QLabel
    QLabel *blue = new QLabel(container);
    blue->setStyleSheet("background: blue");
    blue->show();
}

void MainWindow::changeTabContent() const
{
    // retrieve the QWidget 'container'
    QWidget *container = tab_widget->widget(0);
    // the 'blue' QLabel 
    QWidget *old_content = dynamic_cast<QWidget*>(container->children()[0]); 
    delete old_content;

    // create a red QLabel, as a new content
    QWidget *new_content = new QLabel(container);
    new_content->setStyleSheet("background: red");
    new_content->show();
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    buildTabWidget();
    QPushButton* push_button = new QPushButton("Change content");
    connect(push_button, SIGNAL(clicked(bool)), this, SLOT(changeTabContent()));

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(tab_widget);
    layout->addWidget(push_button);

    QWidget *window = new QWidget();
    window->setLayout(layout);
    window->show();
    setCentralWidget(window);
}

Clicking the button Change content will delete the old content (the blue QLabel) in the tab, and will replace it by creating a new content (a red QLabel):

enter image description here

Upvotes: 4

Related Questions