ragzputin
ragzputin

Reputation: 397

One button connected to two different event methods in PyQT

I'm using PyQT4 to create a GUI. I have a button that needs to connect with one def when a certain condition is met. If this condition is not met, then the button should connect to another def. So far this is what I have -

    if self.txtAgilent.text() and self.txtBattery.text():
        self.connect(self.buttonPlot, SIGNAL('clicked()'), self.plotButtonClicked)
    else:
        self.connect(self.buttonPlot, SIGNAL('clicked()'), self.fileErrorMsgBox)

As above, if the first condition is met (i.e. if two files are selected), a plot is created. If not, an error message box pops up. The problem right now is that whenever I hit the plot button on my GUI, only the error message box pops up even after I have selected two files successfully.

The message box function is as follow:

def fileErrorMsgBox(self):
    w = QWidget()
    msg = QMessageBox.warning(w, "WARNING", "File(s) not chosen! Please choose a file.")

How do I solve this issue?

Upvotes: 0

Views: 283

Answers (1)

three_pineapples
three_pineapples

Reputation: 11869

The best approach is not to try and change the method the button is connected to. Instead, keep the button connected to the same method, and within that method, performs the check (whether things are selected or appropriate text is in text boxes, whatever your use case).

So, for example, something like:

def __init__(self):
    self.connect(self.buttonPlot, SIGNAL('clicked()'), self.plotButtonClicked)

def plotButtonClicked(self):
    if self.txtAgilent.text() and self.txtBattery.text():
        # do what plotButtonClicked did before
    else:
        # create and show the error message box

Note, you should really be using the new style signals/slot API in PyQt which performs connections like this:

self.buttonPlot.clicked.connect(self.plotButtonClicked)

Upvotes: 1

Related Questions