Skip to content

Instantly share code, notes, and snippets.

@mottosso
Last active September 5, 2016 06:46
Show Gist options
  • Save mottosso/89aaa491179baf86f7e7 to your computer and use it in GitHub Desktop.
Save mottosso/89aaa491179baf86f7e7 to your computer and use it in GitHub Desktop.
Restore Script Editor focus

Problem

image

On Windows systems using Autodesk Maya, the text input field of the Script Editor doesn't regain focus after having restored focus to the main window. This event handler explicitly restores focus, if it turns out to have been the last active panel at the time of leaving the application.

Usage

Place the full contents of the script below into your userSetup.py and never again lose focus.

Tested on Maya 2013-2016+ and is safe to use on other platforms where it simply does nothing.

News

try:
from PySide2 import QtCore, QtWidgets
except ImportError:
from PySide import QtCore, QtGui as QtWidgets
class RestoreScriptEditorFocus(QtCore.QObject):
def __init__(self):
super(RestoreScriptEditorFocus, self).__init__()
QtWidgets.qApp.focusChanged.connect(self.on_focuschanged)
self.restore = False
def on_focuschanged(self, old, new):
self.restore = ("cmdScrollFieldExecuter"
in old.objectName() if old else False)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.ApplicationActivate and self.restore:
try:
script_editor = next(
w for w in QtWidgets.qApp.topLevelWidgets()
if w.objectName() == "scriptEditorPanel1Window"
or w.accessibleName() == "Script Editor")
script_editor.activateWindow()
return True
except StopIteration:
# Perhaps the script editor was docked
pass
return super(RestoreScriptEditorFocus, self).eventFilter(obj, event)
f = RestoreScriptEditorFocus()
QtWidgets.qApp.installEventFilter(f)
@ewerybody
Copy link

Nice! Thank you for cooking this! Never understood gist yet..

@mottosso
Copy link
Author

You are most welcome, @ewerybody!

@martin-chatterjee
Copy link

Cheers Marcus, thanks for cooking this up!

On my side this does not work anymore in Maya 2017 (on Windows).
I just had a quick look and the following change/addition seems to work for me (at line 15)

Hope that's helpful to somebody else...

Cheers, Martin

            # (...)
            try:
                script_editor = next(w for w in QtGui.qApp.topLevelWidgets() if w.objectName() == "scriptEditorPanel1Window" or w.accessibleName() == "Script Editor")
                script_editor.activateWindow()
                return True

@martin-chatterjee
Copy link

For the sake of completeness: my previous comment was rubbish, sorry about that... :(

For this to work you also need to:

@mottosso
Copy link
Author

mottosso commented Sep 1, 2016

Thanks @martin-chatterjee! I've updated the gist with your changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment