How to set current tab of QTabWidget by name?
Asked Answered
J

4

26

PyQt5's QTabWidget has a method setCurrentIndex that you can use to get a particular tab to become the active tab. I can't seem to find any way to index by tab name though (which I set in Qt Designer). Is there any way (either direct or indirect) to index by name instead?

http://doc.qt.io/qt-5/qtabwidget.html#currentIndex-prop

Jamshid answered 22/8, 2017 at 23:38 Comment(0)
A
28

The tab name becomes the object-name of the widget set as the tab's page. When the tab is added, the page will be automatically re-parented to the internal stack-widget of the tab-widget. This means you can get a reference to the page like this:

page = tabwidget.findChild(QWidget, tabname)

and get its index like this:

index = tabwidget.indexOf(page)

or set the current tab directly by name like this:

tabwidget.setCurrentWidget(tabwidget.findChild(QWidget, tabname))
Asbestos answered 23/8, 2017 at 0:21 Comment(0)
F
9

An alternative is to remember the tab's index when adding the tab. Then reuse it later in your code:

index = tabWidget.addTab(myWidget)
// ...
tabWidget.setCurrentIndex(index)
Fulcrum answered 24/7, 2018 at 16:39 Comment(0)
Y
7

A method that given a tab_name returns a list of indices for tabs whose names match the tab_name.

def get_indices(tab_name):
    return [index for index in range(tab_widget.count())
        if tab_name == tab_widget.tabText(index)]

After finding the index with this function then standard PyQt methods can be used.

Not the best way to do this, but might be useful sometimes.

Yamada answered 20/8, 2019 at 8:46 Comment(0)
S
1

you can use indexOf() like this :

remove your tab :

self.tabWidget.removeTab(self.tabWidget.indexOf(self.YOUR_TAB_name))

add your tab:

self.tabWidget.addTab(self.YOUR_TAB_name, "name"))
Sidecar answered 20/5, 2020 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.