Search code examples
pythonpython-3.xpyqt4qtabwidget

How can we open a tab specific tab in pyqt on button click?


i have made 10 tabs in my design page using qt designer and have made a menu bar on the top of it. Now i want to connect one of the options in the menubar to a tab (say tab 5). i.e. when i click on menu->button then the tab5 gets opened


Solution

  • To open a tab you must use the setCurrentIndex() method of the QTabWidget, to this method you must indicate the index. The above must be executed each time the triggered signal associated with the QAction of the menu

    class MainWindow(QMainWindow):
        def __init__(self, parent=None):
            QMainWindow.__init__(self, parent)
    
            widget = QTabWidget(self)
            for i in range(10):
                widget.addTab(QListWidget(), "tab{}".format(i+1))
    
            self.setCentralWidget(widget)
    
            menubar = self.menuBar()
            action = menubar.addAction("Select tab5")
            action.triggered.connect(lambda: widget.setCurrentIndex(4))
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())
    

    plus:

        self.Add_GroupD.triggered.connect(lambda checked, index1=4, index2=1 : self.someslot(index1, index2))
    def someslot(self, index1, index2)
        self.tabWidget_4.setCurrentIndex(index1)
        self.tabs.setCurrentIndex(index2)