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?
    Thanks


  • 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):
    super().init()
    self.title = "Hello PyQt5 users"
    self.left = 10
    self.top = 10
    self.width = 640
    self.height = 400
    self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
    
        self.table_widget = MyTableWidget(self)
        self.setCentralWidget(self.table_widget)
    
    
        self.show()
    

    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.resize(300,200)
        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")
        self.tab1.layout.addWidget(self.pushButton1)
        self.tab1.setLayout(self.tab1.layout)
    
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
    
        self.pushButton1.clicked.connect(self.on_click_select_tab2)
    
    def on_click_select_tab2(self):
        QtWidgets.QTabWidget.setCurrentIndex(self.tabs, 1)
    

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

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

    Thanks


  • 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!


Log in to reply
 

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