Python Forum

Full Version: PySide2 Hotkey works only once in Maya
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to open a window that is defined in this script by my custom hotkey, in this case CTRL + TAB. I have this script in Maya(2020):

from PySide2 import QtWidgets, QtCore, QtGui
from PySide2.QtCore import QPropertyAnimation, QEasingCurve, QSize
from PySide2.QtGui import QKeySequence, QIcon, QFont, QPixmap, QWindow
from PySide2.QtWidgets import QDesktopWidget, QAction, QCheckBox, QDialog, QShortcut
from maya import OpenMayaUI
from functools import partial
import maya.cmds as cmds
import sys
import os

try:
	from shiboken import wrapInstance
	import shiboken
except:
	from shiboken2 import wrapInstance
	import shiboken2 as shiboken

class MainWindow(QtWidgets.QMainWindow):
	def __init__(self, parent = None):
		window = OpenMayaUI.MQtUtil.mainWindow()
		mayaWindow = shiboken.wrapInstance(long(window), QtWidgets.QMainWindow)
		super(MainWindow, self).__init__(mayaWindow)

		self.setWindowTitle('Test Window')
		self.setStyleSheet("background-color: rgb(65, 65, 65);")
		self.setWindowFlags(QtCore.Qt.Popup | QtCore.Qt.WindowType.NoDropShadowWindowHint)
		self.resize(630, 400)
		self.releaseKeyboard()
		self.releaseMouse()

		# main widget
		mainWidget = QtWidgets.QWidget(self)
		self.setCentralWidget(mainWidget)

		# layout initialize
		self.mainLayout = QtWidgets.QVBoxLayout()
		mainWidget.setLayout(self.mainLayout)
		self.shortcutSetup()
		self.initialize()


	def shortcutSetup(self):
		QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Escape), self, activated = self.closeWindow)

	def initialize(self, *args):
		cmds.evalDeferred('SetHotkey()', lp = True)

	def closeWindow(self):
		self.hide()


def SetHotkey(*args):
	mayaVersion = cmds.about(version=True)

	operatingSystem = sys.platform
	mainWindow = wrapInstance(long(OpenMayaUI.MQtUtil.mainWindow()), QtWidgets.QWidget)
	launcherAction = QtWidgets.QAction(mainWindow)
	hotkey = 'CTRL + TAB'
	launcherAction.setShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Tab))

	def launcherHotkeyStrike(*args):
		print 'launcherHotkeyStrike'
		cmds.evalDeferred('StartApp()')

	launcherAction.setShortcutContext(QtCore.Qt.ApplicationShortcut)
	print hotkey
	launcherAction.triggered.connect(launcherHotkeyStrike)
	mainWindow.addAction(launcherAction)


def StartApp(*args):
	app = QtWidgets.QApplication.instance()
	if app is None: 
		app = QtWidgets.QApplication(sys.argv)

	w = MainWindow()
	w.show()
	#sys.exit(app.exec_())


if __name__ == '__main__':
	StartApp()
It only works as intended the first time, that means that a window pops up when I run the hotkey but the second time nothing happens. Why is that so?