0
votes

I have an application, in which I have added a QTabWidget. Tabs are closable. When I add new tab, if the tab is already added, it still add new tab and make duplicate. I want to avoid this duplication. If the tab is opened already then It just active that tab and not open again. You help will be appreciated. Thanks

4

4 Answers

2
votes

To add on top of Prakash's answer, be aware that some times the tab title is not a good identifier of the content of the tab (this of course depends on the situation). For example, you might have a file manager where the current directory is the title of the tab, but there might be different directories with the same name across your filesystem.

I would follow the following strategy for identifying tab contents: Qt allows you to set dynamical properties to widgets (see QObject::setProperty), so each time you create a new tab, for example of a file manager, you might do something like

widget = ...
widget->setProperty("tab_dir_fullpath", the_full_path);
tabWidget->addWidget(widget, directory_name);

where the_full_path would be a unique identifier (in this example, the full absolute path to the current directory), which will not be displayed to the user but which you can later use to see if a given directory is already open.

Then, when opening a new tab, you should check whether the same full path is already open:

for (int k = 0; k < tabWidget->count(); ++k) {
  if (tabWidget->widget(k)->property("tab_dir_fullpath").toString() == the_full_path_to_open) {
    tabWidget->setCurrentIndex(k);
    return;
  }
}

... // open new tab, as in the previous snippet.
1
votes

Use tabText(int index) to get the identifier of the each tab before adding a new tab addTab(QWidget * page, const QString & label) and compare the label texts, if already exist just setCurrentIndex of that index or else add a new tab.

0
votes

Also its very good to use setTabData() instead of property which is more proper way of doing.

0
votes

Inspired by Noor Nawaz's comment, my approch is:

    void MainWindow::openPanel1()
    {
        for(int i=0;i<ui->tabWidget->count();i++) {
            if(ui->tabWidget->tabText(i) == "Panel1") {
                ui->tabWidget->setCurrentIndex(i);
                return;
            }
        }
        Panel1 = new panel1Widget();
        int index = ui->tabWidget->addTab(Panel1,"Panel1");
        ui->tabWidget->setCurrentIndex(index);
    }