Last active
June 28, 2016 10:02
-
-
Save timmwagener/a0051f64aac577c4fd0a02d16ad5716c to your computer and use it in GitHub Desktop.
Quick pattern of how to enforce UI singletons.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import logging | |
from PySide import QtGui | |
from PySide import QtCore | |
def delete_instances(widget_type): | |
"""Search for all instances of widget_type and delete them. We find them | |
by class name instead of type since this is safer with all the reload() action | |
used in DCC interpreter sessions. | |
""" | |
widgets = [wdgt for wdgt in QtGui.QApplication.allWidgets() | |
if(widget_type.__name__ == type(wdgt).__name__)] | |
for wdgt in widgets: | |
wdgt.deleteLater() | |
class UISingleton(QtGui.QWidget): | |
def __new__(cls, *args, **kwargs): | |
"""Delete and cleanup old instances.""" | |
delete_instances(cls) | |
return super(UISingleton, cls).__new__(cls, *args, **kwargs) | |
def __init__(self, parent=QtGui.QApplication.activeWindow()): | |
super(UISingleton, self).__init__(parent=parent) | |
name = "{0}.{1}".format(self.__module__, type(self).__name__) | |
self.logger = logging.getLogger(name) | |
self.setWindowTitle("UISingleton") | |
self.setWindowFlags(QtCore.Qt.Window) | |
self.show() | |
if(__name__ == "__main__"): | |
UISingleton() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment