Python: How to to query a current Tab from QTabWidget

alphanumeric picture alphanumeric · Mar 25, 2014 · Viewed 13.7k times · Source

A simple dialog with three tabs: 'Tab_01', 'Tab_02' and 'Tab_03'. Pressing 'What Tab?' button should print what tab is currently active. How to achieve it? (example code posted below):

enter image description here

from PyQt4 import QtGui, QtCore
import sys, os


class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()

        mainWidget=QtGui.QWidget()
        self.setCentralWidget(mainWidget)
        mainLayout = QtGui.QVBoxLayout()
        mainWidget.setLayout(mainLayout)

        self.tabWidget = QtGui.QTabWidget()
        mainLayout.addWidget(self.tabWidget)

        self.tabWidget.connect(self.tabWidget, QtCore.SIGNAL("currentChanged(int)"), self.tabSelected)

        myBoxLayout = QtGui.QVBoxLayout()
        self.tabWidget.setLayout(myBoxLayout)

        self.tabWidget.addTab(QtGui.QWidget(),'Tab_01')
        self.tabWidget.addTab(QtGui.QWidget(),'Tab_02')
        self.tabWidget.addTab(QtGui.QWidget(),'Tab_03')          


        ButtonBox = QtGui.QGroupBox() 
        ButtonsLayout = QtGui.QHBoxLayout()
        ButtonBox.setLayout(ButtonsLayout)

        Button_01 = QtGui.QPushButton("What Tab?")
        ButtonsLayout.addWidget(Button_01)
        Button_01.clicked.connect(self.whatTab)

        mainLayout.addWidget(ButtonBox)


    def tabSelected(self, arg=None):
        print '\n\t tabSelected():', arg

    def whatTab(self):
        print '\n\t current Tab:', '?'


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(480,320)
    sys.exit(app.exec_())

Answer

Hyperboreus picture Hyperboreus · Mar 25, 2014

As you can see here QTabWidget has methods currentIndex and currentWidget.