summaryrefslogtreecommitdiff
path: root/silx/gui/qt/_pyside_dynamic.py
blob: 60134165061d0d9a7f53f8c6c326d40f6b1180b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# -*- coding: utf-8 -*-

# Taken from: https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
# Plus: https://github.com/spyder-ide/qtpy/commit/001a862c401d757feb63025f88dbb4601d353c84

# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
# * customWidgets support (registerCustomWidget() causes segfault in
#   pyside 1.1.2 on Ubuntu 12.04 x86_64)
# * workingDirectory support in loadUi

# found this here:
# https://github.com/lunaryorn/snippets/blob/master/qt4/designer/pyside_dynamic.py

# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

"""
    How to load a user interface dynamically with PySide.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

import logging
import sys

if "PySide.QtCore" in sys.modules:
    from PySide.QtCore import QMetaObject
    from PySide.QtUiTools import QUiLoader
else:  # PySide2
    from PySide2.QtCore import QMetaObject, Property, Qt
    from PySide2.QtWidgets import QFrame
    from PySide2.QtUiTools import QUiLoader

_logger = logging.getLogger(__name__)


class UiLoader(QUiLoader):
    """
    Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface
    in a base instance.

    Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not
    create a new instance of the top-level widget, but creates the user
    interface in an existing instance of the top-level class.

    This mimics the behaviour of :func:`PyQt*.uic.loadUi`.
    """

    def __init__(self, baseinstance, customWidgets=None):
        """
        Create a loader for the given ``baseinstance``.

        The user interface is created in ``baseinstance``, which must be an
        instance of the top-level class in the user interface to load, or a
        subclass thereof.

        ``customWidgets`` is a dictionary mapping from class name to class
        object for widgets that you've promoted in the Qt Designer
        interface. Usually, this should be done by calling
        registerCustomWidget on the QUiLoader, but
        with PySide 1.1.2 on Ubuntu 12.04 x86_64 this causes a segfault.

        ``parent`` is the parent object of this loader.
        """

        QUiLoader.__init__(self, baseinstance)
        self.baseinstance = baseinstance
        self.customWidgets = {}
        self.uifile = None
        self.customWidgets.update(customWidgets)

    def createWidget(self, class_name, parent=None, name=''):
        """
        Function that is called for each widget defined in ui file,
        overridden here to populate baseinstance instead.
        """

        if parent is None and self.baseinstance:
            # supposed to create the top-level widget, return the base instance
            # instead
            return self.baseinstance

        else:
            if class_name in self.availableWidgets():
                # create a new widget for child widgets
                widget = QUiLoader.createWidget(self, class_name, parent, name)

            else:
                # if not in the list of availableWidgets,
                # must be a custom widget
                # this will raise KeyError if the user has not supplied the
                # relevant class_name in the dictionary, or TypeError, if
                # customWidgets is None
                if class_name not in self.customWidgets:
                    raise Exception('No custom widget ' + class_name +
                                    ' found in customWidgets param of' +
                                    'UiFile %s.' % self.uifile)
                try:
                    widget = self.customWidgets[class_name](parent)
                except Exception:
                    _logger.error("Fail to instanciate widget %s from file %s", class_name, self.uifile)
                    raise

            if self.baseinstance:
                # set an attribute for the new child widget on the base
                # instance, just like PyQt*.uic.loadUi does.
                setattr(self.baseinstance, name, widget)

                # this outputs the various widget names, e.g.
                # sampleGraphicsView, dockWidget, samplesTableView etc.
                # print(name)

            return widget

    def _parse_custom_widgets(self, ui_file):
        """
        This function is used to parse a ui file and look for the <customwidgets>
        section, then automatically load all the custom widget classes.
        """
        import importlib
        from xml.etree.ElementTree import ElementTree

        # Parse the UI file
        etree = ElementTree()
        ui = etree.parse(ui_file)

        # Get the customwidgets section
        custom_widgets = ui.find('customwidgets')

        if custom_widgets is None:
            return

        custom_widget_classes = {}

        for custom_widget in custom_widgets.getchildren():

            cw_class = custom_widget.find('class').text
            cw_header = custom_widget.find('header').text

            module = importlib.import_module(cw_header)

            custom_widget_classes[cw_class] = getattr(module, cw_class)

        self.customWidgets.update(custom_widget_classes)

    def load(self, uifile):
        self._parse_custom_widgets(uifile)
        self.uifile = uifile
        return QUiLoader.load(self, uifile)


if "PySide2.QtCore" in sys.modules:

    class _Line(QFrame):
        """Widget to use as 'Line' Qt designer"""
        def __init__(self, parent=None):
            super(_Line, self).__init__(parent)
            self.setFrameShape(QFrame.HLine)
            self.setFrameShadow(QFrame.Sunken)

        def getOrientation(self):
            shape = self.frameShape()
            if shape == QFrame.HLine:
                return Qt.Horizontal
            elif shape == QFrame.VLine:
                return Qt.Vertical
            else:
                raise RuntimeError("Wrong shape: %d", shape)

        def setOrientation(self, orientation):
            if orientation == Qt.Horizontal:
                self.setFrameShape(QFrame.HLine)
            elif orientation == Qt.Vertical:
                self.setFrameShape(QFrame.VLine)
            else:
                raise ValueError("Unsupported orientation %s" % str(orientation))

        orientation = Property("Qt::Orientation", getOrientation, setOrientation)

    CUSTOM_WIDGETS = {"Line": _Line}
    """Default custom widgets for `loadUi`"""

else:  # PySide support
    CUSTOM_WIDGETS = {}
    """Default custom widgets for `loadUi`"""


def loadUi(uifile, baseinstance=None, package=None, resource_suffix=None):
    """
    Dynamically load a user interface from the given ``uifile``.

    ``uifile`` is a string containing a file name of the UI file to load.

    If ``baseinstance`` is ``None``, the a new instance of the top-level widget
    will be created.  Otherwise, the user interface is created within the given
    ``baseinstance``.  In this case ``baseinstance`` must be an instance of the
    top-level widget class in the UI file to load, or a subclass thereof.  In
    other words, if you've created a ``QMainWindow`` interface in the designer,
    ``baseinstance`` must be a ``QMainWindow`` or a subclass thereof, too.  You
    cannot load a ``QMainWindow`` UI file with a plain
    :class:`~PySide.QtGui.QWidget` as ``baseinstance``.

    :method:`~PySide.QtCore.QMetaObject.connectSlotsByName()` is called on the
    created user interface, so you can implemented your slots according to its
    conventions in your widget class.

    Return ``baseinstance``, if ``baseinstance`` is not ``None``. Otherwise
    return the newly created instance of the user interface.
    """
    if package is not None:
        _logger.warning(
            "loadUi package parameter not implemented with PySide")
    if resource_suffix is not None:
        _logger.warning(
            "loadUi resource_suffix parameter not implemented with PySide")

    loader = UiLoader(baseinstance, customWidgets=CUSTOM_WIDGETS)
    widget = loader.load(uifile)
    QMetaObject.connectSlotsByName(widget)
    return widget