0

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
FJ0z13
  • 13
  • 5
  • Can you add a code where you use the `operation_ui` class? – wanderlust Apr 03 '21 at 15:25
  • Can you update your question to contain the minimum reproducible code? It seems a bit hard to guess what's wrong if it's not running. – wanderlust Apr 03 '21 at 15:38
  • how about these? – FJ0z13 Apr 03 '21 at 15:41
  • Much better, but the content of "uiFile.ui" would help much. – wanderlust Apr 03 '21 at 15:43
  • Is it genuinely `print(11111111)` in your code? Because that is trying to print the value of a variable called `11111111` and not literal text. It should be `print('11111111')`. – Alan Apr 03 '21 at 15:45
  • I'm sure `print(111111)` is not a problem. Because no one can use `closeEvent` function – FJ0z13 Apr 03 '21 at 15:50
  • Please, update your question with the working code, and also, update your initial code with all `import` statements. Answers are supposed to be used only for answers to the question, not for the question clarification. – wanderlust Apr 03 '21 at 16:01

1 Answers1

2

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241