Capture window focus in event in Enaml

360 Views Asked by At

Can I execute code when a window comes into focus (becomes the active window, e.g. when the window above it is closed)? I hoped windows would just have focus event or attribute, but that doesn't seem to be the case.

There are focus events in Qt. If Enaml doesn't offer this, what's the easiest way to access these underlying Qt events?

I'd like to be able to do something like:

enamldef MyWindow(Window):
    focus ::
        do_stuff()
1

There are 1 best solutions below

0
On

If you just want to track which widget has focus, you can use a FocusTracker object. Just create an instance of this anywhere, and react to the focused_widget attribute: https://github.com/nucleic/enaml/blob/0f63b494345f2e03ce521adc2c38c6a0ce920266/enaml/widgets/focus_tracker.py

For handling focus on a specif widget, you need to enable the feature flag and reimplement the handler functions: https://github.com/nucleic/enaml/blob/0f63b494345f2e03ce521adc2c38c6a0ce920266/enaml/widgets/widget.py#L88 https://github.com/nucleic/enaml/blob/0f63b494345f2e03ce521adc2c38c6a0ce920266/enaml/widgets/widget.py#L133 https://github.com/nucleic/enaml/blob/0f63b494345f2e03ce521adc2c38c6a0ce920266/enaml/widgets/widget.py#L300-L318

enamldef MyWindow(Window):
    Field:
        features = Feature.FocusEvents
        focus_gained => ():
            print 'got focus'
        focus_lost => ():
            print 'lost focus'

The code is behind a feature flag since the work required by the backend is non-trivial, and we don't want to do that work when it's not necessary.

There aren't any examples of focus handling, but here are some examples working with declarative functions and other "hidden" features like drag-drop: https://github.com/nucleic/enaml/tree/0f63b494345f2e03ce521adc2c38c6a0ce920266/examples/functions https://github.com/nucleic/enaml/blob/0f63b494345f2e03ce521adc2c38c6a0ce920266/examples/widgets/drag_and_drop.enaml