Search code examples
pythonpyqtpyqt5qwizardqwizardpage

Connect QWizard.NextButton to custom method only on the first page


I have a three pages wizard. First page is BasicSettings(), second page is InstallPackages() and the last page is Summary().

I want the Next button on the first page to first execute a method named execute_venv_create() and then call the next page. On the following pages, the Next button should behave as usual.

For this I connected the Next button to execute_venv_create() like this:

class VenvWizard(QWizard):
    """The wizard class."""
    def __init__(self):
        super().__init__()
        # ...

class BasicSettings(QWizardPage):
    """This is the first page."""
    def __init__(self):
        super().__init__()
        # ...

    def initializePage(self):
        next_button = self.wizard().button(QWizard.NextButton)
        next_button.clicked.connect(self.execute_venv_create)

    def execute_venv_create(self):
        # do something, then display an info message
        QMessageBox.information(self, "Done", "message text")

The problem is that of course the method is called every time I click Next and therefore I tried to disconnect the button and reconnect it to the QWizard.next() method in this way:

class InstallPackages(QWizardPage):
    """This is the second page."""
    def __init__(self):
        super().__init__()
        # ...

    def initializePage(self):
        next_button = self.wizard().button(QWizard.NextButton)
        next_button.disconnect()
        next_button.clicked.connect(QWizard.next)

On the first page the Next button works as I expect, it calls the method and switches to the next page. But then, on the second page InstallPackages(), the GUI crashes if I click Next.


Is this the right way to connect a QWizard button to a custom method or is it not possible to use wizard buttons from QWizardPages?

How to connect the QWizard.NextButton to a custom method of a specific QWizardPage and make the button behave as usual on the following pages?


Solution

  • Your method is correct but you have to use the QWizard object associated with the page that can be obtained through the wizard() method:

    def execute_venv_create(self):
        # do something, then display an info message
        QMessageBox.information(self, "Done", "message text")
        next_button = self.wizard().button(QWizard.NextButton)
        next_button.disconnect()
        next_button.clicked.connect(self.wizard().next)