FJ0z13
FJ0z13

Reputation: 13

How to do override closeEvent functions to make it working

I'm using pyside2 and pyqt5 lib to loading my UI file.

from PySide2 import QtWidgets
from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader

class A(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(A, self).__init__(parent)
        self.ui = QUiLoader().load('uiFile.ui')
    
    def closeEvent(self, event):
        event.ignore()


app = QApplication([])
mainWin = A()
mainWin.ui.show()
app.exec_()

In my thought, it will show '11111' when I clicked the X button. However, it's not working at all.

here is the ui file

Upvotes: 0

Views: 1417

Answers (1)

eyllanesc
eyllanesc

Reputation: 243973

The problem is that "A" is a widget that is not displayed, it is not the window, so override closeEvent does not make sense. Instead you should use an event filter to monitor the window's events.

from PySide2.QtCore import QEvent, QObject
from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader


class Manager(QObject):
    def __init__(self, ui, parent=None):
        super(Manager, self).__init__(parent)
        self._ui = ui

        self.ui.installEventFilter(self)

    @property
    def ui(self):
        return self._ui

    def eventFilter(self, obj, event):
        if obj is self.ui:
            if event.type() == QEvent.Close:
                event.ignore()
                return True
        super().eventFilter(obj, event)


def main():
    app = QApplication([])
    manager = Manager(QUiLoader().load("uiFile.ui"))
    manager.ui.show()
    app.exec_()


if __name__ == "__main__":
    main()

If you want to override the closeEvent method of the QMainWindow used in the .ui then you must promote it and register it as this other answer shows.

Upvotes: 2

Related Questions