How can I check which tab is the current one in a tabbed QDockWidget?

You need to find the QTabBar [doc.qt.nokia.com] that exists for the tabbed dockwidgets and then simply call tabBar->currentIndex() [doc.qt.nokia.com] on it to find the current index and connect a slot to the tabbar’s currentChanged() [doc.qt.nokia.com] slot. The example below shows how you can do this.

  1. #include <QtGui>
  2. class MainWindow : public QMainWindow
  3. {
  4.     Q_OBJECT
  5. public:
  6.     MainWindow(QWidget *parent = 0)
  7.         : QMainWindow(parent)
  8.     {
  9.         QWidget *w = new QWidget(this);
  10.         setCentralWidget(w);
  11.         QVBoxLayout *layout = new QVBoxLayout(w);
  12.  
  13.         QDockWidget *d0 = new QDockWidget("Dock 0");
  14.         d0->setFeatures(QDockWidget::NoDockWidgetFeatures);
  15.         d0->setWidget(new QTextEdit);
  16.         QDockWidget *d1 = new QDockWidget("Dock 1");
  17.         d1->setFeatures(QDockWidget::NoDockWidgetFeatures);
  18.         d1->setWidget(new QTextEdit);
  19.         QDockWidget *d2 = new QDockWidget("Dock 2");
  20.         d2->setFeatures(QDockWidget::NoDockWidgetFeatures);
  21.         d2->setWidget(new QTextEdit);
  22.  
  23.         addDockWidget(Qt::LeftDockWidgetArea, d0);
  24.         addDockWidget(Qt::LeftDockWidgetArea, d1);
  25.         addDockWidget(Qt::LeftDockWidgetArea, d2);
  26.  
  27.         tabifyDockWidget(d0, d1);
  28.         tabifyDockWidget(d1, d2);
  29.  
  30.         // get the QTabBar
  31.         QList<QTabBar *> tabList = findChildren<QTabBar *>();
  32.         if(!tabList.isEmpty()){
  33.             QTabBar *tabBar = tabList.at(0);
  34.       tabBar->setCurrentIndex(1);
  35.             QString currentTab = tabBar->tabText(tabBar->currentIndex());
  36.       qDebug() << currentTab;
  37.       connect(tabBar, SIGNAL(currentChanged(int)), this, SLOT(testSlot(int)));
  38.         }
  39.     }
  40.   public slots:
  41.     void testSlot(int index)
  42.     {
  43.       qDebug() << "current tab is " << index;
  44.     }
  45. };
  46.  
  47. #include "main.moc"
  48.  
  49. int main(int argc, char **argv)
  50. {
  51.     QApplication a(argc, argv);
  52.     MainWindow mw;
  53.     mw.show();
  54.     return a.exec();
  55. }
  56.  

2 comments

October 26, 2010

Picture of genjix genjix

Lab Rat

Note that you do not need to bind to a slot to find the current active tab. Simply use tabBar.currentIndex() for getting the current active index and setCurrentIndex(int).

View this thread [developer.qt.nokia.com] for more info.

August 16, 2011

Picture of yunxiaodong yunxiaodong

Lab Rat

when have a qtabbar whitout qdockwidget,how to distinguish?

Write a comment

Sorry, you must be logged in to post a comment.