Nikko
Nikko

Reputation: 1572

Intercepting QDialog closeEvent with functools takes extra argument

I am trying to intercept the closeEvent from a QDialog just like this one. I used functools.partial to call another function inside an object.

class BrowserDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        super(BrowserDialog, self).__init__(parent)
        self.setupUi(self)


class Browser:
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        ...

    def close_event(self):
        pass

    def run(self):
        self.dlg = BrowserDialog()
        self.dlg.closeEvent = functools.partial(self.close_event)

But I get the error:

TypeError: close_event() takes 1 positional argument but 2 were given

What extra arugument am I giving?

Upvotes: 1

Views: 301

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

Do not make foo_object.barEvent = some_function since that method can fail since PyQt has a cache of those methods so your assignment can be ignored, on the other hand the closeEvent method receives a parameter that gives the information of the event. Instead of doing this it is better to create a signal that is the most optimal way to invoke functions in Qt, that signal must be emitted override the closeEvent method.

class BrowserDialog(QtWidgets.QDialog, FORM_CLASS):
    closed = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(BrowserDialog, self).__init__(parent)
        self.setupUi(self)

    def closeEvent(self, event):
        super(BrowserDialog, self).closeEvent(event)
        self.closed.emit()


class Browser:
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        ...

    def handle_closed(self):
        print("closed")

    def run(self):
        self.dlg = BrowserDialog()
        self.dlg.closed.connect(self.handle_closed)

Upvotes: 2

Related Questions