How to disable "Esc quit" when using Qt backend?

114 views
Skip to first unread message

墨焓

unread,
Dec 29, 2020, 2:39:24 AM12/29/20
to Enthought Tool Suite users

By default pressing Esc key will close the window (Qt backend), which is very convenient. But sometimes it is needed to disable this feature, how to do it?

Corran Webster

unread,
Jan 4, 2021, 6:25:32 AM1/4/21
to Enthought Tool Suite users
Hi,

I wasn't even aware that TraitsUI had that behaviour after 10+ years using it!

Looking at the code, it is fairly hard-coded into the View implementation, but you can override it by binding the escape key to a "do nothing" handler using TraitsUI keybindings:

from traits.api import HasTraits, Range
from traitsui.api import View, Item
from traitsui.key_bindings import KeyBinding, KeyBindings


bindings = KeyBindings(
    KeyBinding(
        binding1='Esc',
        description='Stop Escape from closing window',
        method_name='do_nothing',
    )
)


class StopEscapeClosingExample(HasTraits):

    value = Range(0, 100)

    def do_nothing(self, ui_info):
        pass

    traits_view = View(
        Item('value', enabled_when='not _running'),
        key_bindings=bindings,
    )


if __name__ == '__main__':
    example = StopEscapeClosingExample()
    example.configure_traits()

This is not the most elegant solution, but it appears to work.

Hope this helps,

-- Corran

墨焓

unread,
Jan 5, 2021, 1:18:23 AM1/5/21
to Enthought Tool Suite users
Didn't see your reply but thank you for this anyway, it's very helpful.
I was inspired by a slightly "off-topic" post at https://stackoverflow.com/questions/11036985/close-traitsui-window-without-clicking-ok, and ended up with a self-made "wrapper" handler class:
```
#!/usr/bin/env python3
# encoding=utf8
from traits.api import *
from traitsui.api import *
from traitsui.key_bindings import *

from mylib.ez import *

assert Trait


class SimpleHandler(Handler):
def __hdl_do_nothing__(self, *args):
pass

@staticmethod
def __hdl_close_view__(info: UIInfo):
if not info.initialized:
return
info.ui.dispose()

@staticmethod
def __hdl_quit__(*args):
sys.exit()

def __hdl_close_view_and_quit__(self, info: UIInfo):
self.__hdl_close_view__(info)
self.__hdl_quit__()


KB_ESC_NOTHING = KeyBinding(binding1='Esc', method_name=SimpleHandler.__hdl_do_nothing__.__name__)
KB_ESC_CLOSE = KeyBinding(binding1='Esc', method_name=SimpleHandler.__hdl_close_view__.__name__)
KB_ESC_QUIT = KeyBinding(binding1='Esc', method_name=SimpleHandler.__hdl_quit__.__name__)
```
Reply all
Reply to author
Forward
0 new messages