Why is QTabBar giving me the wrong index number?

Viewed 105

So i have two tabs in a tab bar. I have a signal set up so that when clicked, it runs a function. The function calls the current index and prints it.

Why is the print out giving me the index of the page that it WAS on but isn't currently on?

import sys
from PySide2.QtWidgets import *


class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.tabs = QTabBar()
        self.tabs.addTab("Main Menu")
        self.tabs.addTab("Network Menu")

        layout = QHBoxLayout()
        layout.addWidget(self.tabs)

        self.tabs.tabBarClicked.connect(self.tab_push)
        self.setLayout(layout)

    def tab_push(self):
        x = self.tabs.currentIndex()
        print(x)

app = QApplication(sys.argv)

window = Window()
window.show()

sys.exit(app.exec_())

The indentation is a bit weird, not sure why thats happened, but it works nevertheless.

1 Answers

That is not an error but normal behavior: When the tabbar is pressed the index is obtained, the signal tabBarClicked is emitted, then the currentIndex is changed, then there is a time between the signal is emitted and the currectIndex is updated, which is in that moment that you are making the impression. If you want to get the index of the pressed tab then use the signal information:

def tab_push(self, index):
    print(index)
Related