How can I add a “new tab” button next to the tabs of a QMdiArea in tabbed view mode?

后端 未结 5 1196
天命终不由人
天命终不由人 2020-12-05 14:46

I\'d like to have a \"new tab\" button much like Chrome or Firefox has for my QMdiArea.

I can make a button or menu item somewhere that adds a new subdo

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 15:26

    First, add an empty tab to your widget, and connect the currentChanged signal:

    TabsView::TabsView(QWidget *parent) :
      QWidget(parent),
      ui(new Ui::TabsView)
    {
        ui->setupUi(this);
        ui->tabWidget->clear();
        ui->tabWidget->addTab(new QLabel("+"), QString("+"));
        connect(ui->tabWidget, &QTabWidget::currentChanged, this, &TabsView::onChangeTab);
        newTab();
    }
    

    Then, on your onChangeTab slot, check if the user is clicking on the last tab, and call newTab:

    void TabsView::onChangeTab(int index)
    {
        if (index == this->ui->tabWidget->count() - 1) {
            newTab();
        }
    }
    

    Finally, on your newTab method, create the new tab and select it:

    void TabsView::newTab()
    {
        int position = ui->tabWidget->count() - 1;
        ui->tabWidget->insertTab(position, new QLabel("Your new tab here"), QString("New tab"));
        ui->tabWidget->setCurrentIndex(position);
        auto tabBar = ui->tabWidget->tabBar();
        tabBar->scroll(tabBar->width(), 0);
    }
    

提交回复
热议问题