How to switch tab under PyQt5

  • Hi,
    I am migrating from PyQt4 to PyQt5 and have corrected most of my code apart from one method which is no longer working:
    I need to switch tabs in my app and the foolowing method used to work under PyQt4:
    QTabWidget.setCurrentIndex(self.tabWidget, 0) # to open the first tab
    QTabWidget.setCurrentIndex(self.tabWidget, 1) # to open the second tab

    I could not make it workunder PyQt5… What is the correct syntax under PyQt5?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You should share the code you are using.

  • Hi,
    here is the code I am using:

    import sys
    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    import time

    class App(QMainWindow):
    def init(self):
    self.title = "Hello PyQt5 users"
    self.left = 10 = 10
    self.width = 640
    self.height = 400

    def initUI(self):
        self.setGeometry(self.left,, self.width, self.height)
        self.table_widget = MyTableWidget(self)

    class MyTableWidget(QWidget):
    def init(self, parent):
    super(QWidget, self).init(parent)
    self.layout = QVBoxLayout(self)

        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.addTab(self.tab1, "Tab 1")
        self.tabs.addTab(self.tab2, "Tab 2")
        self.tab1.layout = QVBoxLayout(self)
        self.pushButton1 = QPushButton("Press here to open Tab 2")
    def on_click_select_tab2(self):
        QtWidgets.QTabWidget.setCurrentIndex(self.tabs, 1)

    if name == 'main':
    app = QApplication(sys.argv)
    ex = App()

    The tab 2 never gets selected and the windows shutdown with the message "Process finished with exit code 3"


  • Lifetime Qt Champion

    Why aren't you calling self.tabs.setCurrentIndex(1) ?

    on_click_select_tab2 implementation doesn't really make sense. You seem to try to call a method from a class and pass it an object and a parameter. setCurrentIndex is not a static method, it's an object method.

  • @SGaist

    Hello SGaist, thanks a lot for your explanation. It works great!


Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.