is there a way to detect if user trying to close window? For example, in Tkinter we can do something like this:
def exit_dialog(): #do stuff pass root = Tk() root.protocol("WM_DELETE_WINDOW", exit_dialog) root.mainloop()
Thanks.
PySide is LGPL while PyQt is GPL. This could make a difference if you don't wish to make your project opensource. Although PyQt always has the propriety version available for a fairly reasonable price. I tend to find the PySide documentation more intuitive.
Advantages of PySide PySide represents the official set of Python bindings backed up by the Qt Company. PySide comes with a license under the LGPL, meaning it is simpler to incorporate into commercial projects when compared with PyQt. It allows the programmer to use QtQuick or QML to establish the user interface.
The short answer is that the reason lies mainly in license related issues and that PyQt and PySide are actually very similar, so similar that the code below for a QT based version of the miles-to-kilometers converter works with both PyQt and PySide. For PySide you only have to replace the import line at the beginning.
The simplest way to close a window is to click the right (Windows) or left (macOS) 'X' button on the title bar.
Override the closeEvent
method of QWidget
in your main window.
For example:
class MainWindow(QWidget): # or QMainWindow ... def closeEvent(self, event): # do stuff if can_exit: event.accept() # let the window close else: event.ignore()
Another possibility is to use the QApplication
's aboutToQuit
signal like this:
app = QApplication(sys.argv) app.aboutToQuit.connect(myExitHandler) # myExitHandler is a callable
If you just have one window (i.e the last window) you want to detect then you can use the setQuitOnLastWindowClosed
static function and the lastWindowClosed
signal.
from PySide2 import QtGui import sys def keep_alive(): print("ah..ah..ah..ah...staying alive...staying alive") window.setVisibility(QtGui.QWindow.Minimized) if __name__ == '__main__': app = QtGui.QGuiApplication() app.setQuitOnLastWindowClosed(False) app.lastWindowClosed.connect(keep_alive) window = QtGui.QWindow() window.show() sys.exit(app.exec_())
Hope that helps someone, it worked for me as on my first attempt I couldn't override closeEvent(), lack of experience!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With