Reputation: 211
I having the problem that every time I press the hotkey(in this case CTRL + A) I open a new window and the old one does not disappear.
I have added a random color and random position into the code so you the new windows. Use the script in Maya:
from PySide2 import QtWidgets, QtCore, QtGui
from PySide2.QtGui import QKeySequence
from PySide2.QtWidgets import QShortcut
from maya import OpenMayaUI
import sys
from random import randrange
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')
#Set a random color:
self.setStyleSheet('background-color: rgb(' + str(randrange(255)) + ', ' + str(randrange(255)) + ', ' + str(randrange(255)) + ');')
self.setWindowFlags(QtCore.Qt.Popup | QtCore.Qt.WindowType.NoDropShadowWindowHint)
self.resize(630, 400)
self.releaseKeyboard()
self.releaseMouse()
self._window = None
#Set a random position:
self.setGeometry(randrange(800), randrange(800), randrange(800), randrange(800))
# main widget
mainWidget = QtWidgets.QWidget(self)
self.setCentralWidget(mainWidget)
def mousePressEvent(self, QMouseEvent):
closeOnLostFocus = True
if closeOnLostFocus:
xPosition = QMouseEvent.pos().x()
yPosition = QMouseEvent.pos().y()
width = self.width()
height = self.height()
if xPosition > self.width() or xPosition < 0:
self.closeWindow()
if yPosition > self.height() or yPosition < 0:
self.closeWindow()
def showWindow(self):
self.closeWindow()
if self._window is None:
self._window = MainWindow()
self._window.show()
def closeWindow(self):
self.close()
def setHotkey(*args):
hotkey = ''
window = window = OpenMayaUI.MQtUtil.mainWindow()
mayaWindow = shiboken.wrapInstance(long(window), QtWidgets.QMainWindow)
hotkey = 'CTRL + A'
shortcut = QShortcut(QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_A), mayaWindow)
shortcut.setContext(QtCore.Qt.ApplicationShortcut)
shortcut.activated.connect(startApp)
return hotkey
def startApp(*args):
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.showWindow()
setHotkey()
I would like that a new window appears and the one created before that disappears, so that only one exists at a time.
Upvotes: 0
Views: 1154
Reputation: 244282
You have to have a single variable that stores the only object, that's why I have created a global variable:
mainWindow = None
def startApp(*args):
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
global mainWindow
mainWindow = MainWindow()
mainWindow.show()
setHotkey()
Upvotes: 2