Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PyQt : Checking the current widget

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading