Home > other >  PyQt : Checking the current widget
PyQt : Checking the current widget

Time:12-08

I'm using QStackwidget and I want to check if I'm in Widget A or B. In PyQt Documentation, it says that I will need currentwidget() method which will return the current widget/page. This is the output of this method in python :

print(self.ui.stackedWidget.currentWidget()) 

The console shows the following :

<PyQt5.QtWidgets.QWidget object at 0x0000203A1009160> 

So it's showing the address of the widget that I'm currently in.

But what I want to implement is the following

if self.ui.stackedWidget.currentWidget() == page A:
   #action1
elif self.ui.stackedWidget.currentWidget() == page B:
   #action2
and so on ...

Is there way to get the page name through currentWidget() method ?

CodePudding user response:

QStackedWidget.currentWidget() gives you the widget itself so you can compare it directly:

firstPageWidget = QWidget()
secondPageWidget = QWidget()
thirdPageWidget = QWidget()

stackedWidget = QStackedWidget()
stackedWidget.addWidget(firstPageWidget)
stackedWidget.addWidget(secondPageWidget)
stackedWidget.addWidget(thirdPageWidget)

currentWidget = stackedWidget.currentWidget()

if currentWidget == firstPageWidget:
    print("In first page")
elif currentWidget == secondPageWidget:
    print("In second page")
elif currentWidget == thirdPageWidget:
    print("In third page")

The method QStackedWidget::currentIndex() might also be useful as it returns the index of the current widget and not the widget itself.

  • Related