Reputation: 966
I'm trying to ask the user for confirmation when he tries to quit my application. But I don't know how to catch all the different ways the user can quit the app: there's the 'X' button on the window, Alt+F4, I myself use Alt+Shift+Q on i3.
How would one go o about this?
Upvotes: 4
Views: 2156
Reputation: 8805
You should connect to the delete-event
of the Gtk.Window
you use at the application window. The delete-event
allows you to show a confirmation dialog, and, depending on the user response, you can either return True
— meaning that you handled the event, and that the signal propagation should be stopped; or return False
— meaning that the signal propagation should continue, which will cause the destroy()
method to be called on the widget.
The delete-event
signal is emitted in response of a termination request from the window manager; for instance, when using the window menu; a key combination like Alt+F4; or the window's "Close" button.
A simple example demonstrating the above:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gio
from gi.repository import Gtk
class AppWindow (Gtk.ApplicationWindow):
def __init__(self):
Gtk.ApplicationWindow.__init__(self)
self.set_default_size(200, 200)
# Override the default handler for the delete-event signal
def do_delete_event(self, event):
# Show our message dialog
d = Gtk.MessageDialog(transient_for=self,
modal=True,
buttons=Gtk.ButtonsType.OK_CANCEL)
d.props.text = 'Are you sure you want to quit?'
response = d.run()
d.destroy()
# We only terminate when the user presses the OK button
if response == Gtk.ResponseType.OK:
print('Terminating...')
return False
# Otherwise we keep the application open
return True
def on_activate(app):
# Show the application window
win = AppWindow()
win.props.application = app
win.show()
if __name__ == '__main__':
# Create an application instance
app = Gtk.Application(application_id='com.example.ExampleApp', flags=0)
# Use ::activate to show our application window
app.connect('activate', on_activate)
app.run()
Upvotes: 7