Accelerators: add ctrl-q without menus

I’m doing my first steps with wxPython and I don’t manage to add ctrl-q to quit my simple App.

Following https://wxpython.org/Phoenix/docs/html/wx.AcceleratorTable.html I came up with:

#!/usr/bin/env python
import wx


class Test(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Test')


class App(wx.App):
    """App doing a calculation."""

    def OnInit(self):
        self.frame = Test()
        self.frame.Show()

        entries = [wx.AcceleratorEntry() for i in range(1)]
        entries[0].Set(wx.ACCEL_CTRL, ord('Q'), wx.ID_EXIT)
        accel = wx.AcceleratorTable(entries)
        self.frame.SetAcceleratorTable(accel)

        return True

if __name__ == '__main__':
    app = App(False)
    app.MainLoop()

It compiles and run, but ctrl-q has no effect…

Any hint?

Based on https://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators/

#!/usr/bin/env python

import wx

class Test(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Test')
        panel = wx.Panel(self)

        ctrl_q_id = wx.NewIdRef()
        self.Bind(wx.EVT_MENU, self.OnCtrlQ, id=ctrl_q_id)
        acc_table = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('Q'), ctrl_q_id)])
        self.SetAcceleratorTable(acc_table)

    def OnCtrlQ(self, event):
        print("You pressed Ctrl-Q")
        self.Destroy()


class App(wx.App):
    """App doing a calculation."""

    def OnInit(self):
        self.frame = Test()
        self.frame.Show()
        return True


if __name__ == '__main__':
    app = App(False)
    app.MainLoop()

[This works on Python 3.8.5 + wxPython 4.1.1 gtk3 (phoenix) wxWidgets 3.1.5 + Linux Mint 20.1].

thaks @RichardT !

yes that works!

but it feels a bit like a hack. attaching a shortcut to a menu that does not really exixt.

i’ve used a few of UI toolkits and almost all of them had a simple and documented way to quit application with ESC, ctrl-w and/or ctrl-q (sometimes it was even automatically setup).

i guess that it would be a nice add to wxpython to provide an easy way to close a simple application that does not have a menu : - )

have wonderful start to the week
a.l.e

That is how the accelerator table is designed. It simply changes the shortcut into a menu event. Since the menu events usually come from the frame, not the menubar, then it doesn’t need to have a menubar to work this way. When there is a menubar then the accelerators embedded in the menu items can use the same internal functionality.