Search code examples
pythonpython-3.xpyqtpyqt5

PyQt5 distinguish ok and cancel command


This is dialog code using PyQt5 QDialog.

class QDialogUI(QDialog):
    def __init__(self):

        super().__init__()

        self.okButton = QPushButton("Ok", self)
        self.okButton.clicked.connect(self.acceptCommand)
        self.okButton.clicked.connect(lambda:self.closeCommand(1))

        self.cancelButton = QPushButton("Cancel", self)
        self.cancelButton.clicked.connect(lambda:self.closeCommand(0))

    def acceptCommand(self):
        ...
        return date, asset, sort, money, text

    def closeCommand(self, status):
        return status

And this is main code.

def openDialog(self):
    self.dlg = QDialogUI()
    self.dlg.exec_()
    if self.dlg.closeCommand() == 1:
        iD = list(self.dlg.acceptCommand())
        self.params.emit(iD[0],iD[1],iD[2],iD[3],iD[4])

If I clicked okButton or cancelButton, Both of them don't react. And I close QDialogUI, it shows error like:

TypeError: closeCommand()missing 1 required positional argument: 'status'

How can I get 'return of acceptCommand' when 'okButton.clicked'?
Or is there more better code that distinguish ok and cancel command?


Solution

  • The solution is to create an attribute of the class that saves that information when it is pressed and that can be used later:

    class QDialogUI(QDialog):
        def __init__(self):
            super().__init__()
            self.status = None
            self.okButton = QPushButton("Ok", self)
            self.okButton.clicked.connect(self.acceptCommand)
            self.okButton.clicked.connect(lambda:self.closeCommand(1))
    
            self.cancelButton = QPushButton("Cancel", self)
            self.cancelButton.clicked.connect(lambda:self.closeCommand(0))
    
        def acceptCommand(self):
            ...
            self.status = date, asset, sort, money, text
    
        def closeCommand(self, status):
            return self.status