Search code examples
qtqpushbuttonqtabwidgetqt5.5

How to open other tab of same window using a pushbutton on qt?


I have a window. In this window I have a tab. In this tab I have two pages (page 1 & page 2). I have a pushButton on page 1. I one to go on page 2 using this pushButton. How to open other tab of same window using a pushbutton on qt?

enter image description here

mainwindow.h

  #ifndef MAINWINDOW_H
  #define MAINWINDOW_H

  #include <QMainWindow>

 QT_BEGIN_NAMESPACE
 namespace Ui { class MainWindow; }
 QT_END_NAMESPACE

 class MainWindow : public QMainWindow
 {
    Q_OBJECT

    public:
   MainWindow(QWidget *parent = nullptr);
   ~MainWindow();

   private slots:
   void on_pushButton_clicked();

   private:
       Ui::MainWindow *ui;
   };
   #endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"

#include <QApplication>

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

mainwindow.cpp

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

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

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


    void MainWindow::on_pushButton_clicked()
    {

     }

Solution

  • From the comments: One solution is to add an automatic slot in your main window class that executes when the button is clicked. In this slot have it change the current index of the QTabWidget.

    For example the following should cycle throw the tabs every time you click the button:

    void MainWindow::on_pushButton_clicked() 
    {
       if (ui->tabWidget->count() > 1) {
          ui->tabWidget->setCurrentIndex( (ui->tabWidget->currentIndex()+1) % ui->tabWidget->count() );
       }
    }