qtqt5qpushbuttonqstackedwidget

stack widget pages using pushbutton in Qt


How to navigate QStackWidget pages using QPushButtons? Which method needs to be called whenever pushbutton is clicked, so that it opens a particluar stackwidget page.

Thanks & Regards,


Solution

  • QStackedWidget has a method .setCurrentIndex(int) which you can use to switch to a different page. You can use that method in combination with clicked() signal of QPushButton to change the current stacked widget page.

    Example:

    MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        //initially set current page to 0
        ui->stackedWidget->setCurrentIndex(0);
    
        //suppose we have buttons button1 and button2
        connect(button1, &QPushButton::clicked, this, [=]() {
            //set page to 1
            ui->stackedWidget->setCurrentIndex(1);
        });
    
        connect(button2, &QPushButton::clicked, this, [=]() {
            //set page to 2
            ui->stackedWidget->setCurrentIndex(2);
        });
    
    }
    

    You can also use normal function slots instead of lambda functions:

    //mainwindow.h file
    
    class MainWindow{
    //...
    private slots:
      void onButton1Clicked();
      void onButton2Clicked();
    }
    
    //mainwindow.cpp file
    
    MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
    {
      //...
        connect(button1, &QPushButton::clicked, this, &MainWindow::onButton1Clicked);
        connect(button2, &QPushButton::clicked, this, &MainWindow::onButton2Clicked);
    }
    
    void MainWindow::onButton1Clicked()
    {
      ui->stackedWidget->setCurrentIndex(1);
    }
    
    void MainWindow::onButton2Clicked()
    {
      ui->stackedWidget->setCurrentIndex(1);
    }