简体   繁体   English

QTabWidget setCurrentIndex无法按预期工作

[英]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. 如果满足某个条件,当用户单击QTabWidget的第二个选项卡时,我试图将视图更改为主选项卡,但是当我在on_tabWidget_tabBarClicked()内调用setCurrentIndex() on_tabWidget_tabBarClicked() ,视图将保留在当前选项卡上。 Please see the code below. 请参阅下面的代码。

If I call setCurrentIndex() outside of on_tabWidget_tabBarClicked() , then it works. 如果我在on_tabWidget_tabBarClicked() setCurrentIndex()之外调用setCurrentIndex() on_tabWidget_tabBarClicked() ,那么它可以工作。

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

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: 您的情况下的问题是,当信号被触发时,即使您的鼠标位于QTabWidget上,因此即使您使用setCurrentIndex(0)更改选项卡,鼠标事件也会将其更改回1.在这种情况下逻辑是更改它片刻之后,使用了QTimer:

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

Using the slot on_tabWidget_currentChanged instead of tabBarClicked would also work correctly since this is called once the tab change is complete. 使用插槽on_tabWidget_currentChanged而不是tabBarClicked也可以正常工作,因为一旦选项卡更改完成就会调用它。 That would avoid the need to call the asynchronous QTimer. 这样可以避免调用异步QTimer的需要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM