Bryan Hsieh
Bryan Hsieh

Reputation: 33

QTabWidget setCurrentIndex not working as expected

I am trying to change the view to the main tab when a user clicks on the second tab of QTabWidget if a certain condition is met, but when I call setCurrentIndex() inside of on_tabWidget_tabBarClicked(), the view stays on the current tab. Please see the code below.

If I call setCurrentIndex() outside of on_tabWidget_tabBarClicked(), then it works.

void MainWindow::on_tabWidget_tabBarClicked(int index)
{
    if (index == 1)
    {
        Error("Empty, back to main");
        ui->tabWidget->setCurrentIndex(0);
    }
}

Upvotes: 3

Views: 1405

Answers (2)

Mike Z
Mike Z

Reputation: 21

Using the slot on_tabWidget_currentChanged instead of tabBarClicked would also work correctly since this is called once the tab change is complete. That would avoid the need to call the asynchronous QTimer.

void MainWindow::on_tabWidget_currentChanged(int index)
{
    if (index == 1)
    {
        Error("Empty, back to main");
        ui->tabWidget->setCurrentIndex(0);
    }
}

Upvotes: 1

eyllanesc
eyllanesc

Reputation: 244282

The problem in your case is that when the signal is triggered even your mouse is on the QTabWidget so even if you change the tab with setCurrentIndex(0) then the mouse event will change it back to 1. In this case the logic is change it a moment later and for this a QTimer is used:

void MainWindow::on_tabWidget_tabBarClicked(int index)
{
   if(index==1)
   {
       Error("Empty, back to main");
       QTimer::singleShot(100, [this](){ ui->tabWidget->setCurrentIndex(0); });
   }
}

Upvotes: 1

Related Questions