Qt中TabWidget控件获取tab索引遇到的问题
- 在Qt中常用的两个信号是:currentChanged(int index)和tabBarClicked(int index),这两个函数的意思是当当前tab改变时触发和当tab被点击时触发。
- 但是在上面这两个信号中使用currentIndex()函数获取索引时会出现两种不同的结果,这个结果非常容易导致程序有bug,下面简单记录一下。
在currentChanged(int index)函数中添加如下代码:
int cnt = ui->tabWidget->currentIndex();
qDebug() << "********currentChanged(int index)********";
qDebug() << "currentIndex() index: " << cnt;
qDebug() << "currentChanged index: " << index;
在tabBarClicked(int index)函数中添加如下代码:
int cnt = ui->tabWidget->currentIndex();
qDebug() << "********tabBarClicked(int index)********";
qDebug() << "currentIndex() index: " << cnt;
qDebug() << "tabBarClicked index: " << index;
则启动Qt窗口应用程序的时候对tab进行切换,在currentChanged(int index)函数中的ui->tabWidget->currentIndex()函数得到的索引是切换之后的,而tabBarClicked(int index)函数中的ui->tabWidget->currentIndex()函数得到的索引是切换之前的。如果原来的索引时0,则点击切换到索引1之后代码输出的结果是:
********tabBarClicked(int index)********
currentIndex() index: 0
tabBarClicked index: 1
********currentChanged(int index)********
currentIndex() index: 1
currentChanged index: 1
这里跟实际的不一样,所以最后如果需要获取tab的索引,还是建议直接使用信号当中的index参数,这个参数就是切换之后的索引值。