Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PySide / PyQt detect if user trying to close window

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.

like image 299
SaulTigh Avatar asked Feb 12 '12 14:02

SaulTigh


People also ask

Is PySide better than PyQt?

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.

Why use PySide instead of PyQt?

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.

Is PySide and PyQt the same?

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.

How do I close a PyQt5 window?

The simplest way to close a window is to click the right (Windows) or left (macOS) 'X' button on the title bar.


2 Answers

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 
like image 127
Oleh Prypin Avatar answered Sep 21 '22 14:09

Oleh Prypin


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!

like image 22
mcdixon Avatar answered Sep 17 '22 14:09

mcdixon