コード例 #1
0
    def on_transparentStyle_clicked(self):
        styleSheet = QFile(":/files/transparent.qss")

        if not styleSheet.open(QIODevice.ReadOnly):
            print("Unable to open :/files/transparent.qss")
            return

        QApplication.instance().setStyleSheet(styleSheet.readAll().data().decode())
コード例 #2
0
ファイル: item.py プロジェクト: tpDcc/tpDcc-tools-datalibrary
    def setIcon(self, column, icon, color=None):
        """
        Overrides base QTreeWidgetItem setIcon function
        :param column: int or str
        :param icon: QIcon
        :param color: QColor or None
        """

        is_app_running = bool(QApplication.instance())
        if not is_app_running:
            return

        if python.is_string(icon):
            if not os.path.exists(icon):
                color = color or QColor(255, 255, 255, 20)
                icon = resources.icon('image', color=color)
            else:
                icon = QIcon(icon)
        if python.is_string(column):
            self._icon[column] = icon
        else:
            self._pixmap[column] = None
            super(ItemView, self).setIcon(column, icon)

        self.update_icon()
コード例 #3
0
 def copy_csv(self):
     """put CSV data for current tab on the clipboard"""
     app = QApplication.instance()
     clipboard = app.clipboard()
     csv = self.get_csv()
     clipboard.setText(csv)
     self.session.logger.status("copied to clipboard")
コード例 #4
0
 def setUp(self):
     try:
         self.qtApp = QApplication([])
     except RuntimeError:
         self.qtApp = QApplication.instance()
     self.gui = SimpleGui()
     QApplication.processEvents()
コード例 #5
0
ファイル: pyblish_lite_nuke.py プロジェクト: tws0002/Nuke-2
def setup():
    panels.register(Window, '发布', 'com.wlf.pyblish')

    callback.CALLBACKS_ON_SCRIPT_LOAD.append(
        lambda: pyblish_action('validate', is_block=True, is_reset=True))
    callback.CALLBACKS_ON_SCRIPT_SAVE.append(
        lambda: pyblish_action('validate', is_block=False, is_reset=True))
    callback.CALLBACKS_ON_SCRIPT_CLOSE.append(abort_modified(
        lambda: pyblish_action('publish', is_block=True, is_reset=False)))

    # Remove default plugins.
    pyblish.plugin.deregister_all_paths()
    try:
        settings.TerminalLoglevel = int(
            logging.getLevelName(os.getenv('LOGLEVEL')))
    except (TypeError, ValueError):
        settings.TerminalLoglevel = 20

    app.install_fonts()
    app.install_translator(QApplication.instance())
    set_preferred_fonts('微软雅黑', 1.2)

    for mod in (pyblish_cgtwn, pyblish_asset):
        for i in pyblish.plugin.plugins_from_module(mod):
            pyblish.plugin.register_plugin(i)
コード例 #6
0
    def icon(self, *names, **kwargs):
        """Return a QIcon object corresponding to the provided icon name."""
        options_list = kwargs.pop('options', [{}] * len(names))
        general_options = kwargs

        if len(options_list) != len(names):
            error = '"options" must be a list of size {0}'.format(len(names))
            raise Exception(error)

        if QApplication.instance() is not None:
            parsed_options = []
            for i in range(len(options_list)):
                specific_options = options_list[i]
                parsed_options.append(self._parse_options(specific_options,
                                                          general_options,
                                                          names[i]))

            # Process high level API
            api_options = parsed_options

            return self._icon_by_painter(self.painter, api_options)
        else:
            warnings.warn("You need to have a running "
                          "QApplication to use QtAwesome!")
            return QIcon()
コード例 #7
0
def application():
    """Get QApplication instance, create one if needed.  """

    app = QApplication.instance()

    if not app:
        app = QApplication(sys.argv)
    return app
コード例 #8
0
def init(dev=False):
    """
    Initializes module
    :param dev: bool, Whether tpDcc-libs-qt is initialized in dev mode or not
    """

    logger = create_logger(dev=dev)

    # NOTE: We register all classes using tpDcc register (not tpDcc.libs.qt one).
    # # We do it in this way to access those classes easily
    # dcc_register.register_class('InputsMgr', inputs_manager.InputsManagerSingleton)
    # dcc_register.register_class('ToolsetsMgr', toolsets_manager.ToolsetsManagerSingleton)

    def init_dcc():
        """
        Checks DCC we are working on an initializes proper variables
        """

        dcc_loaded = False
        try:
            if 'cmds' in main.__dict__:
                from tpDcc.dccs.maya import loader as dcc_loader
                dcc_loaded = True
            elif 'MaxPlus' in main.__dict__:
                from tpDcc.dccs.max import loader as dcc_loader
                dcc_loaded = True
            elif 'hou' in main.__dict__:
                from tpDcc.dccs.houdini import loader as dcc_loader
                dcc_loaded = True
            elif 'nuke' in main.__dict__:
                from tpDcc.dccs.nuke import loader as dcc_loader
                dcc_loaded = True
            else:
                try:
                    import unreal
                    from tpDcc.dccs.unreal import loader as dcc_loader
                    dcc_loaded = True
                except Exception:
                    pass
        except ImportError:
            logger.warning(
                'Impossible to setup DCC. DCC not found. Abstract one will be used.'
            )
        except Exception as exc:
            logger.warning(
                'Error while setting DCC: {}. Abstract one will be used.'.
                format(exc))

        if dcc_loaded:
            if hasattr(dcc_loader, 'init_ui') and callable(dcc_loader.init_ui):
                dcc_loader.init_ui()

    app = QApplication.instance() or QApplication(sys.argv)

    update_paths()

    init_dcc()
コード例 #9
0
ファイル: contexts.py プロジェクト: tpDcc/tpDcc-libs-qt
def application():
    app = QApplication.instance()
    if not app:
        app = QApplication(sys.argv)
        yield app
        app.exec_()
    else:
        yield app
        if dcc.is_standalone():
            app.exec_()
コード例 #10
0
def desktop_pixmap_from_rect(rect):
    """
    Generates a pixmap of the application desktop in the given rect
    :param rect: QRect
    :return: QPixmap
    """

    desktop = QApplication.instance().desktop()

    return QPixmap.grabWindow(desktop.winId(), rect.x(), rect.y(),
                              rect.width(), rect.height())
コード例 #11
0
ファイル: xsiInterface.py プロジェクト: phmongeau/Simplex
def rootWindow():
	"""
	Returns the currently active QT main window
	Only works for QT UI's like Maya
	"""
	# for MFC apps there should be no root window
	window = None
	if QApplication.instance():
		inst = QApplication.instance()
		window = inst.activeWindow()
		# Ignore QSplashScreen's, they should never be considered the root window.
		if isinstance(window, QSplashScreen):
			return None
		# If the application does not have focus try to find A top level widget
		# that doesn't have a parent and is a QMainWindow or QDialog
		if window == None:
			windows = []
			dialogs = []
			for w in QApplication.instance().topLevelWidgets():
				if w.parent() == None:
					if isinstance(w, QMainWindow):
						windows.append(w)
					elif isinstance(w, QDialog):
						dialogs.append(w)
			if windows:
				window = windows[0]
			elif dialogs:
				window = dialogs[0]

		# grab the root window
		if window:
			while True:
				parent = window.parent()
				if not parent:
					break
				if isinstance(parent, QSplashScreen):
					break
				window = parent

	return window
コード例 #12
0
def walk_pykrita_dir():
    try:
        this_dir = os.path.dirname(sys.argv[0])
        pykrita_dir = os.path.join(this_dir, "..", "pykrita")
        for parent, folders, files in os.walk(pykrita_dir):
            for file in files:
                if file.lower() == "readme.md":
                    readme_path = os.path.join(parent, file)
                    embed_readme_images(readme_path)
        print("done!")
    finally:
        app = QApplication.instance()
        app.quit()
コード例 #13
0
    def __init__(self, project_name):
        self.project_name = project_name
        self._app = QApplication.instance()
        self._css_filepath = None

        self.main_window = QWidget()
        self.main_window.setWindowFlags(Qt.Tool)
        self.main_window.setWindowTitle("CSS Editor - " + self.project_name)

        self.variables = Variables()
        self.variables.changed.connect(self._variables_changed)
        self.variables.changed.connect(self._render_and_apply)

        self.template = CSSTextEdit()
        self.template.changed.connect(self._template_changed)
        self.template.changed.connect(self._render_and_apply)

        self.save = QPushButton('Save stylesheet to')
        self.save.clicked.connect(self._save_stylesheet)

        self.save_destination = QLineEdit()
        self.save_destination.textChanged.connect(self._destination_changed)

        self.splitter = QSplitter()
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.addWidget(self.variables)
        self.splitter.addWidget(self.template)

        layout = QGridLayout(self.main_window)
        layout.addWidget(self.splitter, 0, 0, 1, 2)
        layout.addWidget(self.save, 1, 0)
        layout.addWidget(self.save_destination, 1, 1)

        self.main_window.resize(800, 600)

        self._project_dir = self._ensure_project_dir()
        self._top_level_widgets = [
            widget for widget in QApplication.topLevelWidgets() if
            widget.windowTitle() != self.main_window.windowTitle()
        ]
        self._variables = dict()
        self._template = None
        self._stylesheet = ""

        self._app.aboutToQuit.connect(self._save_editor_state)
        self._open()
        self.save_destination.setText(self.css_filepath)
        self.main_window.show()
コード例 #14
0
def app():
    """
    Context to create a Qt app
    >>> with with qtutils.app():
    >>>     w = QWidget(None)
    >>>     w.show()
    :return:
    """

    app_ = None
    is_app_running = bool(QApplication.instance())
    if not is_app_running:
        app_ = QApplication(sys.argv)
        install_fonts()

    yield None

    if not is_app_running:
        sys.exit(app_.exec_())
コード例 #15
0
    def load_font(self, prefix, ttf_filename, charmap_filename, directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """

        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            id_ = QFontDatabase.addApplicationFont(os.path.join(directory,
                                                                ttf_filename))
            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
            if(loadedFontFamilies):
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                        os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                md5_hashes = {'fontawesome4.7-webfont.ttf':
                              'b06871f281fee6b241d60582ae9369b9',
                              'fontawesome5-regular-webfont.ttf':
                              '73fe7f1effbf382f499831a0a9f18626',
                              'fontawesome5-solid-webfont.ttf':
                              '0079a0ab6bec4da7d6e16f2a2e87cd71',
                              'fontawesome5-brands-webfont.ttf':
                              '947b9537bc0fecc8130d48eb753495a1',
                              'elusiveicons-webfont.ttf':
                              '207966b04c032d5b873fd595a211582e',
                              'materialdesignicons-webfont.ttf':
                              '64b96825d49e070ea87c7100f2db3f46'}
                ttf_hash = md5_hashes.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                                        os.path.join(directory, ttf_filename)))
コード例 #16
0
 def copy_csv(self):
     app = QApplication.instance()
     clipboard = app.clipboard()
     csv = self.get_csv()
     clipboard.setText(csv)
     self.session.logger.status("copied to clipboard")
コード例 #17
0
ファイル: __init__.py プロジェクト: tpDcc/tpDcc-libs-qt
from Qt.QtWidgets import QApplication


def create_logger(dev=False):
    """
    Creates logger for current tpDcc-libs-qt package
    """

    logger_directory = os.path.normpath(
        os.path.join(os.path.expanduser('~'), 'tpDcc', 'logs', 'libs'))
    if not os.path.isdir(logger_directory):
        os.makedirs(logger_directory)

    logging_config = os.path.normpath(
        os.path.join(os.path.dirname(__file__), '__logging__.ini'))

    logging.config.fileConfig(logging_config, disable_existing_loggers=False)
    logger = logging.getLogger('tpDcc-libs-qt')
    dev = os.getenv('TPDCC_DEV', dev)
    if dev:
        logger.setLevel(logging.DEBUG)
        for handler in logger.handlers:
            handler.setLevel(logging.DEBUG)

    return logger


create_logger()

app = QApplication.instance() or QApplication(sys.argv)
コード例 #18
0
    def load(cls):

        app = QApplication.instance() or QApplication(sys.argv)
        resources_path = os.path.dirname(
            os.path.dirname(os.path.abspath(__file__)))
        resources.register_resource(resources_path, key='tpDcc-libs-resources')
コード例 #19
0
def has_gui():
    """Return if running in gui envrionment.  """

    return HAS_QT and isinstance(QApplication.instance(), QApplication)
コード例 #20
0
 def propertyEditingFinished(self):
     le = QApplication.instance().focusWidget()
     if isinstance(le, QLineEdit):
         nodeName, attr = le.objectName().split('.')
         Pin = self.getPinByName(attr)
         Pin.setData(le.text())
コード例 #21
0
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                try:
                    result[key] = chr(int(obj[key], 16))
                except ValueError:
                    if int(obj[key], 16) > 0xffff:
                        # ignoring unsupported code in Python 2.7 32bit Windows
                        # ValueError: chr() arg not in range(0x10000)
                        pass
                    else:
                        raise FontError(u'Failed to load character '
                                        '{0}:{1}'.format(key, obj[key]))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            with open(os.path.join(directory, ttf_filename),
                      'rb') as font_data:
                id_ = QFontDatabase.addApplicationFontFromData(
                    QByteArray(font_data.read()))
            font_data.close()

            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)

            if loadedFontFamilies:
                self.fontids[prefix] = id_
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                ttf_hash = MD5_HASHES.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                            os.path.join(directory, ttf_filename)))
コード例 #22
0
def load_plugins():
    """Loads plugins from the puglins folder"""

    plugins = PluginManager()
    plugins_folder = os.path.join(os.environ['LOOKDEVTOOLS'], 'python',
                                  'ldtplugins')
    print plugins_folder
    plugins.setPluginPlaces([plugins_folder])
    plugins.collectPlugins()
    plugins.locatePlugins()
    logger.info('Plugin candidates %s' % plugins.getPluginCandidates())
    for pluginInfo in plugins.getAllPlugins():
        plugins.activatePluginByName(pluginInfo.name)
        logger.info('Plugin activated %s' %
                    plugins.activatePluginByName(pluginInfo.name))
    return plugins


add_ldt_menus()

plugins = load_plugins()

main_window = QApplication.instance()
if main_window:
    app = main_window
else:
    app = QApplication(sys.argv)
ldt_window = ldtui.LDTWindow(plugins)
ldt_window.show()
コード例 #23
0
ファイル: buttons.py プロジェクト: tpDcc/tpDcc-libs-qt
    def __init__(self,
                 icon=None,
                 icon_hover=None,
                 text=None,
                 parent=None,
                 double_click_enabled=False,
                 menu_padding=5,
                 menu_align=Qt.AlignLeft):
        """

        :param icon:
        :param icon_hover:
        :param text:
        :param parent:
        :param double_click_enabled:
        """

        self.idleIcon = icon or QIcon()
        self.hoverIcon = icon_hover or QIcon()

        super(BaseMenuButton, self).__init__(icon=self.idleIcon,
                                             text=text,
                                             parent=parent)

        self._menu_active = {
            Qt.LeftButton: True,
            Qt.MidButton: True,
            Qt.RightButton: True
        }

        self._click_menu = {
            Qt.LeftButton: None,
            Qt.MidButton: None,
            Qt.RightButton: None
        }

        self._menu_searchable = {
            Qt.LeftButton: False,
            Qt.MidButton: False,
            Qt.RightButton: False
        }

        self._last_click = None
        self._icon_color = None
        self._menu_padding = menu_padding
        self._menu_align = menu_align

        self.leftClicked.connect(partial(self._on_context_menu, Qt.LeftButton))
        self.middleClicked.connect(partial(self._on_context_menu,
                                           Qt.MidButton))
        self.rightClicked.connect(
            partial(self._on_context_menu, Qt.RightButton))

        app = QApplication.instance()
        if app and hasattr(app, 'doubleClickInterval') and callable(
                app.doubleClickInterval):
            self._double_click_interval = QApplication.instance(
            ).doubleClickInterval()
        else:
            self._double_click_interval = 500
        self._double_click_enabled = double_click_enabled