0

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,

Waqar
  • 8,558
  • 4
  • 35
  • 43

1 Answers1

1

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);
}
Waqar
  • 8,558
  • 4
  • 35
  • 43
  • what's that after (clicked,this, ) "[=]"? –  Jun 16 '20 at 06:23
  • It's a lambda function. It's like a function with no name. You can use normal function here, but it needs to be declared under `slots:` in `MainWindow` class. – Waqar Jun 16 '20 at 06:26
  • @MdMoslehUddin see the updated answer with function slots – Waqar Jun 16 '20 at 06:30
  • it says button1 isn't declared in this scope. (i tried 2nd method) –  Jun 16 '20 at 14:40
  • yes, you have to use the variable names that you have set. check your `.ui` file for the variable names. This is just an example. Your variable will probably be under `ui->` – Waqar Jun 16 '20 at 14:53