Laurent Crivello
Laurent Crivello

Reputation: 3931

Closable QTabWidget tabs, but not all of them

In a Qt/C++ piece of code, I have a QTabWidget class with different tabs. I would like to add a last "+" tab, so when the user is clicking on it, I create a new tab.
However I would like to have all my tabs closable ('x' at the right of the tab), except the last one where I don't want the 'x' to be displayed. How can I have this granularity in the closable flag ?

Upvotes: 2

Views: 2895

Answers (1)

Nithish
Nithish

Reputation: 1640

Surprised to see that this is not yet answered. Had some time and I have implemented a working example. Note that instead of using one of the tabs as your "+" button, I have used QToolButton thereby making it simpler to make tabs closable with QTabWidget::setTabsClosable(bool)

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTabWidget>
#include <QToolButton>
#include <QLabel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::MainWindow *ui;
    QTabWidget* _pTabWidget;

private slots:
    void slotAddTab();
    void slotCloseTab(int);
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    _pTabWidget = new QTabWidget(this);
    this->setCentralWidget(_pTabWidget);

    // Create button what must be placed in tabs row
    QToolButton* tb = new QToolButton(this);
    tb->setText("+");

    // Add empty, not enabled tab to tabWidget
    _pTabWidget->addTab(new QLabel("Add tabs by pressing \"+\""), QString());
    _pTabWidget->setTabEnabled(0, false);

    // Add tab button to current tab. Button will be enabled, but tab -- not
    _pTabWidget->tabBar()->setTabButton(0, QTabBar::RightSide, tb);

    // Setting tabs closable and movable
    _pTabWidget->setTabsClosable(true);
    _pTabWidget->setMovable(true);
    connect(tb,SIGNAL(clicked()),this,SLOT(slotAddTab()));
    connect(_pTabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT(slotCloseTab(int)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotAddTab()
{
    QWidget* newTab = new QWidget(_pTabWidget);
    _pTabWidget->addTab(newTab, tr("Tab %1").arg(QString::number(_pTabWidget->count())));
    _pTabWidget->setCurrentWidget(newTab);
}

void MainWindow::slotCloseTab(int index)
{
    delete _pTabWidget->widget(index);
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Upvotes: 4

Related Questions