Example #1
0
    def setFormatter(self, formatter):
        """Set the formatter object to be used to display data from the model

        :param TextFormatter formatter: Formatter to use
        """
        if formatter is self.__formatter:
            return

        if qt.qVersion() > "4.6":
            self.beginResetModel()

        if self.__formatter is not None:
            self.__formatter.formatChanged.disconnect(self.__formatChanged)

        self.__formatter = formatter
        self.__editFormatter = TextFormatter(formatter)
        self.__editFormatter.setUseQuoteForText(False)

        if self.__formatter is not None:
            self.__formatter.formatChanged.connect(self.__formatChanged)

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
Example #2
0
    def setFormatter(self, formatter):
        """Set the formatter object to be used to display data from the model

        :param TextFormatter formatter: Formatter to use
        """
        if formatter is self.__formatter:
            return

        if qt.qVersion() > "4.6":
            self.beginResetModel()

        if self.__formatter is not None:
            self.__formatter.formatChanged.disconnect(self.__formatChanged)

        self.__formatter = formatter
        self.__editFormatter = TextFormatter(formatter)
        self.__editFormatter.setUseQuoteForText(False)

        if self.__formatter is not None:
            self.__formatter.formatChanged.connect(self.__formatChanged)

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
    def mouseReleaseEvent(self, event):
        point1 = self.pos()
        deltax = point1.x() - self._point0.x()
        deltay = point1.y() - self._point0.y()
        self.moveBy(-deltax, -deltay)
        parent = self.parentItem()

        # deduce scale from rectangle
        if (qt.qVersion() < "5.0") or self.keepRatio:
            scalex = self._newRect.rect().width() / self._w
            scaley = scalex
        else:
            scalex = self._newRect.rect().width() / self._w
            scaley = self._newRect.rect().height() / self._h

        if qt.qVersion() < "5.0":
            parent.scale(scalex, scaley)
        else:
            # apply the scale to the previous transformation matrix
            previousTransform = parent.transform()
            parent.setTransform(
                    previousTransform.scale(scalex, scaley))

        self.scene().removeItem(self._newRect)
        self._newRect = None
        qt.QGraphicsRectItem.mouseReleaseEvent(self, event)
    def setArrayData(self, data):
        """Set the data array and the viewing perspective.

        You can set ``copy=False`` if you need more performances, when dealing
        with a large numpy array. In this case, a simple reference to the data
        is used to access the data, rather than a copy of the array.

        .. warning::

            Any change to the data model will affect your original data
            array, when using a reference rather than a copy..

        :param data: 1D numpy array, or any object that can be
            converted to a numpy array using ``numpy.array(data)`` (e.g.
            a nested sequence).
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()

        self.__data = data
        if isinstance(data, numpy.ndarray):
            self.__is_array = True
        elif silx.io.is_dataset(data) and data.shape != tuple():
            self.__is_array = True
        else:
            self.__is_array = False

        self.__fields = []
        if data is not None:
            if data.dtype.fields is not None:
                fields = sorted(data.dtype.fields.items(),
                                key=lambda e: e[1][1])
                for name, (dtype, _index) in fields:
                    if dtype.shape != tuple():
                        keys = itertools.product(
                            *[range(x) for x in dtype.shape])
                        for key in keys:
                            label = "%s%s" % (name, list(key))
                            array_key = (name, key)
                            self.__fields.append((label, array_key))
                    else:
                        self.__fields.append((name, (name, )))
            else:
                self.__fields = None

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
    def setData1(self):
        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        content = {}
        content[0, 0] = ("title", True, (1, 3))
        content[0, 1] = ("a", True, (2, 1))
        content[1, 1] = ("b", False, (1, 2))
        content[1, 2] = ("c", False, (1, 1))
        content[2, 2] = ("d", False, (1, 1))
        self.__content = content
        if qt.qVersion() > "4.6":
            self.endResetModel()
    def setData1(self):
        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        content = {}
        content[0, 0] = ("title", True, (1, 3))
        content[0, 1] = ("a", True, (2, 1))
        content[1, 1] = ("b", False, (1, 2))
        content[1, 2] = ("c", False, (1, 1))
        content[2, 2] = ("d", False, (1, 1))
        self.__content = content
        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #7
0
File: utils.py Project: vallsv/silx
    def configure(self, parsed_options):
        """Configure the TestOptions class from the command line arguments and the
        environment variables
        """
        if not parsed_options.gui:
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "Skipped by command line"
        elif os.environ.get('WITH_QT_TEST', 'True') == 'False':
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "Skipped by WITH_QT_TEST env var"
        elif sys.platform.startswith('linux') and not os.environ.get('DISPLAY', ''):
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "DISPLAY env variable not set"

        if not parsed_options.opencl or os.environ.get('SILX_OPENCL', 'True') == 'False':
            self.WITH_OPENCL_TEST = False
            # That's an easy way to skip OpenCL tests
            # It disable the use of OpenCL on the full silx project
            os.environ['SILX_OPENCL'] = "False"

        if not parsed_options.opengl:
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "Skipped by command line"
        elif os.environ.get('WITH_GL_TEST', 'True') == 'False':
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "Skipped by WITH_GL_TEST env var"

        if parsed_options.low_mem or os.environ.get('SILX_TEST_LOW_MEM', 'True') == 'False':
            self.TEST_LOW_MEM = True

        if self.WITH_QT_TEST:
            from silx.gui import qt
            if sys.platform == "win32" and qt.qVersion() == "5.9.2":
                self.SKIP_TEST_FOR_ISSUE_936 = True
Example #8
0
    def setData(self, data):
        """Set the h5py-like object exposed by the model

        :param data: A h5py-like object. It can be a `h5py.Dataset`,
            a `h5py.File`, a `h5py.Group`. It also can be a,
            `silx.gui.hdf5.H5Node` which is needed to display some local path
            information.
        """
        model = self.model()

        model.setObject(data)
        header = self.horizontalHeader()
        if qt.qVersion() < "5.0":
            setResizeMode = header.setResizeMode
        else:
            setResizeMode = header.setSectionResizeMode
        setResizeMode(0, qt.QHeaderView.Fixed)
        setResizeMode(1, qt.QHeaderView.ResizeToContents)
        setResizeMode(2, qt.QHeaderView.Stretch)
        setResizeMode(3, qt.QHeaderView.ResizeToContents)
        setResizeMode(4, qt.QHeaderView.ResizeToContents)
        header.setStretchLastSection(False)

        for row in range(model.rowCount()):
            for column in range(model.columnCount()):
                index = model.index(row, column)
                if (index.isValid() and index.data(
                        HierarchicalTableView.HierarchicalTableModel.IsHeaderRole) is False):
                    self.openPersistentEditor(index)
    def mousePressEvent(self, event):
        if self._newRect is not None:
            self._newRect = None
        self._point0 = self.pos()
        parent = self.parentItem()
        scene = self.scene()
        # following line prevents dragging along the previously selected
        # item when resizing another one
        scene.clearSelection()

        rect = parent.boundingRect()
        self._x = rect.x()
        self._y = rect.y()
        self._w = rect.width()
        self._h = rect.height()
        self._ratio = self._w / self._h
        if qt.qVersion() < "5.0":
            self._newRect = qt.QGraphicsRectItem(parent, scene)
        else:
            self._newRect = qt.QGraphicsRectItem(parent)
        self._newRect.setRect(qt.QRectF(self._x,
                                        self._y,
                                        self._w,
                                        self._h))
        qt.QGraphicsRectItem.mousePressEvent(self, event)
Example #10
0
    def __init__(self, parent=None):
        """Constructor"""
        qt.QTreeView.__init__(self, parent=None)
        self.__model = _Model(self)
        self.__model.setColumnCount(4)
        self.__model.setHorizontalHeaderLabels(["Name", "Dataset", "Type", "Shape"])
        self.setModel(self.__model)

        self.setItemDelegateForColumn(1, _HashDropZones(self))

        self.__model.sigNxdataUpdated.connect(self.__nxdataUpdate)
        self.__model.rowsAboutToBeRemoved.connect(self.__rowsAboutToBeRemoved)
        self.__model.rowsAboutToBeInserted.connect(self.__rowsAboutToBeInserted)

        header = self.header()
        if qt.qVersion() < "5.0":
            setResizeMode = header.setResizeMode
        else:
            setResizeMode = header.setSectionResizeMode
        setResizeMode(0, qt.QHeaderView.ResizeToContents)
        setResizeMode(1, qt.QHeaderView.Stretch)
        setResizeMode(2, qt.QHeaderView.ResizeToContents)
        setResizeMode(3, qt.QHeaderView.ResizeToContents)

        self.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self.setDropIndicatorShown(True)
        self.setDragDropOverwriteMode(True)
        self.setDragEnabled(True)
        self.viewport().setAcceptDrops(True)

        self.setContextMenuPolicy(qt.Qt.CustomContextMenu)
        self.customContextMenuRequested[qt.QPoint].connect(self.__executeContextMenu)
Example #11
0
    def setArrayData(self, data):
        """Set the data array and the viewing perspective.

        You can set ``copy=False`` if you need more performances, when dealing
        with a large numpy array. In this case, a simple reference to the data
        is used to access the data, rather than a copy of the array.

        .. warning::

            Any change to the data model will affect your original data
            array, when using a reference rather than a copy..

        :param data: 1D numpy array, or any object that can be
            converted to a numpy array using ``numpy.array(data)`` (e.g.
            a nested sequence).
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()

        self.__data = data
        if isinstance(data, numpy.ndarray):
            self.__is_array = True
        elif silx.io.is_dataset(data) and data.shape != tuple():
            self.__is_array = True
        else:
            self.__is_array = False

        self.__fields = []
        if data is not None:
            if data.dtype.fields is not None:
                fields = sorted(data.dtype.fields.items(), key=lambda e: e[1][1])
                for name, (dtype, _index) in fields:
                    if dtype.shape != tuple():
                        keys = itertools.product(*[range(x) for x in dtype.shape])
                        for key in keys:
                            label = "%s%s" % (name, list(key))
                            array_key = (name, key)
                            self.__fields.append((label, array_key))
                    else:
                        self.__fields.append((name, (name,)))
            else:
                self.__fields = None

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
Example #12
0
    def configure(self, parsed_options=None):
        """Configure the TestOptions class from the command line arguments and the
        environment variables
        """
        if parsed_options is not None and not parsed_options.gui:
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "Skipped by command line"
        elif os.environ.get('WITH_QT_TEST', 'True') == 'False':
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "Skipped by WITH_QT_TEST env var"
        elif sys.platform.startswith('linux') and not os.environ.get('DISPLAY', ''):
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "DISPLAY env variable not set"

        if parsed_options is not None and not parsed_options.opencl:
            self.WITH_OPENCL_TEST_REASON = "Skipped by command line"
            self.WITH_OPENCL_TEST = False
        elif os.environ.get('SILX_OPENCL', 'True') == 'False':
            self.WITH_OPENCL_TEST_REASON = "Skipped by SILX_OPENCL env var"
            self.WITH_OPENCL_TEST = False

        if not self.WITH_OPENCL_TEST:
            # That's an easy way to skip OpenCL tests
            # It disable the use of OpenCL on the full silx project
            os.environ['SILX_OPENCL'] = "False"

        if parsed_options is not None and not parsed_options.opengl:
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "Skipped by command line"
        elif os.environ.get('WITH_GL_TEST', 'True') == 'False':
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "Skipped by WITH_GL_TEST env var"
        elif sys.platform.startswith('linux') and not os.environ.get('DISPLAY', ''):
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "DISPLAY env variable not set"
        else:
            try:
                import OpenGL
            except ImportError:
                self.WITH_GL_TEST = False
                self.WITH_GL_TEST_REASON = "OpenGL package not available"

        if parsed_options is not None and parsed_options.low_mem:
            self.TEST_LOW_MEM = True
            self.TEST_LOW_MEM_REASON = "Skipped by command line"
        elif os.environ.get('SILX_TEST_LOW_MEM', 'True') == 'False':
            self.TEST_LOW_MEM = True
            self.TEST_LOW_MEM_REASON = "Skipped by SILX_TEST_LOW_MEM env var"

        if self.WITH_QT_TEST:
            try:
                from silx.gui import qt
            except ImportError:
                self.WITH_QT_TEST = False
                self.WITH_QT_TEST_REASON = "Qt is not installed"
            else:
                if sys.platform == "win32" and qt.qVersion() == "5.9.2":
                    self.SKIP_TEST_FOR_ISSUE_936 = True
    def setFrameAxes(self, row_axis, col_axis):
        """Set the perspective by specifying the two axes parallel to the frame
        to be visualised.

        The complementary approach of defining the orthogonal axes can be used
        with :meth:`setPerspective`.

        :param int row_axis: Index (0-based) of the first dimension used as a frame
            axis
        :param int col_axis: Index (0-based) of the 2nd dimension used as a frame
            axis
        :raise: IndexError if axes are invalid
        """
        if row_axis > col_axis:
            _logger.warning("The dimension of the row axis must be lower " +
                            "than the dimension of the column axis. Swapping.")
            row_axis, col_axis = min(row_axis,
                                     col_axis), max(row_axis, col_axis)

        n_dimensions = len(self._array.shape)
        if n_dimensions < 3:
            _logger.warning(
                "Frame axes cannot be changed for 1D and 2D arrays")
            return

        perspective = tuple(set(range(0, n_dimensions)) - {row_axis, col_axis})

        if len(perspective) != n_dimensions - 2 or\
                min(perspective) < 0 or max(perspective) >= n_dimensions:
            raise IndexError("Invalid perspective " + str(perspective) +
                             " for %d-D array " % n_dimensions +
                             "with shape " + str(self._array.shape))

        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        self._perspective = perspective
        # reset index
        self._index = [0 for _i in range(n_dimensions - 2)]

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #14
0
    def setFrameAxes(self, row_axis, col_axis):
        """Set the perspective by specifying the two axes parallel to the frame
        to be visualised.

        The complementary approach of defining the orthogonal axes can be used
        with :meth:`setPerspective`.

        :param int row_axis: Index (0-based) of the first dimension used as a frame
            axis
        :param int col_axis: Index (0-based) of the 2nd dimension used as a frame
            axis
        :raise: IndexError if axes are invalid
        """
        if row_axis > col_axis:
            _logger.warning("The dimension of the row axis must be lower " +
                            "than the dimension of the column axis. Swapping.")
            row_axis, col_axis = min(row_axis, col_axis), max(row_axis, col_axis)

        n_dimensions = len(self._array.shape)
        if n_dimensions < 3:
            _logger.warning(
                    "Frame axes cannot be changed for 1D and 2D arrays")
            return

        perspective = tuple(set(range(0, n_dimensions)) - {row_axis, col_axis})

        if len(perspective) != n_dimensions - 2 or\
                min(perspective) < 0 or max(perspective) >= n_dimensions:
            raise IndexError(
                    "Invalid perspective " + str(perspective) +
                    " for %d-D array " % n_dimensions +
                    "with shape " + str(self._array.shape))

        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        self._perspective = perspective
        # reset index
        self._index = [0 for _i in range(n_dimensions - 2)]

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #15
0
 def __updateColumnConstraints(self):
     header = self.horizontalHeader()
     if qt.qVersion() < "5.0":
         setResizeMode = header.setResizeMode
     else:
         setResizeMode = header.setSectionResizeMode
     setResizeMode(0, qt.QHeaderView.Stretch)
     setResizeMode(1, qt.QHeaderView.ResizeToContents)
     setResizeMode(2, qt.QHeaderView.ResizeToContents)
     setResizeMode(3, qt.QHeaderView.Fixed)
Example #16
0
 def __updateColumnConstraints(self):
     header = self.horizontalHeader()
     if qt.qVersion() < "5.0":
         setResizeMode = header.setResizeMode
     else:
         setResizeMode = header.setSectionResizeMode
     setResizeMode(0, qt.QHeaderView.Stretch)
     setResizeMode(1, qt.QHeaderView.ResizeToContents)
     setResizeMode(2, qt.QHeaderView.ResizeToContents)
     setResizeMode(3, qt.QHeaderView.Fixed)
Example #17
0
 def setData(self, data):
     widget = self.getWidget()
     widget.model().setObject(data)
     header = widget.horizontalHeader()
     if qt.qVersion() < "5.0":
         setResizeMode = header.setResizeMode
     else:
         setResizeMode = header.setSectionResizeMode
     setResizeMode(0, qt.QHeaderView.Fixed)
     setResizeMode(1, qt.QHeaderView.Stretch)
     header.setStretchLastSection(True)
    def setFrameIndex(self, index):
        """Set the active slice index.

        This method is only relevant to arrays with at least 3 dimensions.

        :param index: Index of the active slice in the array.
            In the general n-D case, this is a sequence of :math:`n - 2`
            indices where the slice intersects the respective orthogonal axes.
        :raise IndexError: If any index in the index sequence is out of bound
            on its respective axis.
        """
        shape = self._array.shape
        if len(shape) < 3:
            # index is ignored
            return

        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        if len(shape) == 3:
            len_ = shape[self._perspective[0]]
            # accept integers as index in the case of 3-D arrays
            if not hasattr(index, "__len__"):
                self._index = [index]
            else:
                self._index = index
            if not 0 <= self._index[0] < len_:
                raise ValueError("Index must be a positive integer " +
                                 "lower than %d" % len_)
        else:
            # general n-D case
            for i_, idx in enumerate(index):
                if not 0 <= idx < shape[self._perspective[i_]]:
                    raise IndexError("Invalid index %d " % idx +
                                     "not in range 0-%d" % (shape[i_] - 1))
            self._index = index

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #19
0
    def setFrameIndex(self, index):
        """Set the active slice index.

        This method is only relevant to arrays with at least 3 dimensions.

        :param index: Index of the active slice in the array.
            In the general n-D case, this is a sequence of :math:`n - 2`
            indices where the slice intersects the respective orthogonal axes.
        :raise IndexError: If any index in the index sequence is out of bound
            on its respective axis.
        """
        shape = self._array.shape
        if len(shape) < 3:
            # index is ignored
            return

        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        if len(shape) == 3:
            len_ = shape[self._perspective[0]]
            # accept integers as index in the case of 3-D arrays
            if not hasattr(index, "__len__"):
                self._index = [index]
            else:
                self._index = index
            if not 0 <= self._index[0] < len_:
                raise ValueError("Index must be a positive integer " +
                                 "lower than %d" % len_)
        else:
            # general n-D case
            for i_, idx in enumerate(index):
                if not 0 <= idx < shape[self._perspective[i_]]:
                    raise IndexError("Invalid index %d " % idx +
                                     "not in range 0-%d" % (shape[i_] - 1))
            self._index = index

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #20
0
    def setArrayData(self, data):
        """Set the data array.

        :param data: A numpy object or a dataset.
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()

        self.__connector = None
        self.__data = data
        if self.__data is not None:
            if silx.io.utils.is_dataset(self.__data):
                data = data[()]
            elif isinstance(self.__data, numpy.ndarray):
                data = data[()]
            self.__connector = _VoidConnector(data)

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
Example #21
0
    def setArrayData(self, data):
        """Set the data array.

        :param data: A numpy object or a dataset.
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()

        self.__connector = None
        self.__data = data
        if self.__data is not None:
            if silx.io.utils.is_dataset(self.__data):
                data = data[()]
            elif isinstance(self.__data, numpy.ndarray):
                data = data[()]
            self.__connector = _VoidConnector(data)

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
Example #22
0
    def setObject(self, h5pyObject):
        """Set the h5py-like object exposed by the model

        :param h5pyObject: A h5py-like object. It can be a `h5py.Dataset`,
            a `h5py.File`, a `h5py.Group`. It also can be a,
            `silx.gui.hdf5.H5Node` which is needed to display some local path
            information.
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()

        if h5pyObject is None or self.isSupportedObject(h5pyObject):
            self.__obj = h5pyObject
        else:
            _logger.warning("Object class %s unsupported. Object ignored.", type(h5pyObject))
        self.__initProperties()

        if qt.qVersion() > "4.6":
            self.endResetModel()
        else:
            self.reset()
Example #23
0
    def __fixHeader(self):
        """Update the view according to the state of the auto-resize"""
        header = self.horizontalHeader()
        if qt.qVersion() < "5.0":
            setResizeMode = header.setResizeMode
        else:
            setResizeMode = header.setSectionResizeMode

        header.setDefaultSectionSize(30)
        header.setStretchLastSection(True)
        for i in range(0x10):
            setResizeMode(i, qt.QHeaderView.Fixed)
        setResizeMode(0x10, qt.QHeaderView.Stretch)
Example #24
0
    def testAvoidRestoreRegression_Version1(self):
        version = qt.qVersion().split(".")[0]
        if version == "4":
            state = self.STATE_VERSION1_QT4
        elif version == "5":
            state = self.STATE_VERSION1_QT5
        else:
            self.skipTest("Resource not available")

        state = qt.QByteArray(state)
        dialog = self.createDialog()
        result = dialog.restoreState(state)
        self.assertTrue(result)
Example #25
0
    def testAvoidRestoreRegression_Version1(self):
        version = qt.qVersion().split(".")[0]
        if version == "4":
            state = self.STATE_VERSION1_QT4
        elif version == "5":
            state = self.STATE_VERSION1_QT5
        else:
            self.skipTest("Resource not available")

        state = qt.QByteArray(state)
        dialog = self.createDialog()
        result = dialog.restoreState(state)
        self.assertTrue(result)
Example #26
0
    def __fixHeader(self):
        """Update the view according to the state of the auto-resize"""
        header = self.horizontalHeader()
        if qt.qVersion() < "5.0":
            setResizeMode = header.setResizeMode
        else:
            setResizeMode = header.setSectionResizeMode

        header.setDefaultSectionSize(30)
        header.setStretchLastSection(True)
        for i in range(0x10):
            setResizeMode(i, qt.QHeaderView.Fixed)
        setResizeMode(0x10, qt.QHeaderView.Stretch)
Example #27
0
    def __updateText(self):
        """Update the content of the dialog according to the settings."""
        import silx._version

        message = """<table>
        <tr><td width="50%" align="center" valign="middle">
            <img src="{silx_image_path}" width="100" />
        </td><td width="50%" align="center" valign="middle">
            <b>{application_name}</b>
            <br />
            <br />{silx_version}
            <br />
            <br /><a href="{project_url}">Upstream project on GitHub</a>
        </td></tr>
        </table>
        <dl>
            <dt><b>Silx version</b></dt><dd>{silx_version}</dd>
            <dt><b>Qt version</b></dt><dd>{qt_version}</dd>
            <dt><b>Qt binding</b></dt><dd>{qt_binding}</dd>
            <dt><b>Python version</b></dt><dd>{python_version}</dd>
            <dt><b>Optional libraries</b></dt><dd>{optional_lib}</dd>
        </dl>
        <p>
        Copyright (C) <a href="{esrf_url}">European Synchrotron Radiation Facility</a>
        </p>
        """
        optional_lib = []
        optional_lib.append(
            self.__formatOptionalLibraries("FabIO", fabio is not None))
        optional_lib.append(
            self.__formatOptionalLibraries("H5py", h5py is not None))
        optional_lib.append(
            self.__formatOptionalLibraries("hdf5plugin", hdf5plugin
                                           is not None))

        # Access to the logo in SVG or PNG
        logo = icons.getQFile("../logo/silx")

        info = dict(application_name=self.__applicationName,
                    esrf_url="http://www.esrf.eu",
                    project_url="https://github.com/silx-kit/silx",
                    silx_version=silx._version.version,
                    qt_binding=qt.BINDING,
                    qt_version=qt.qVersion(),
                    python_version=sys.version.replace("\n", "<br />"),
                    optional_lib="<br />".join(optional_lib),
                    silx_image_path=logo.fileName())

        self.__label.setText(message.format(**info))
        self.__updateSize()
Example #28
0
    def mouseReleaseEvent(self, event):
        point1 = self.pos()
        deltax = point1.x() - self._point0.x()
        deltay = point1.y() - self._point0.y()
        self.moveBy(-deltax, -deltay)
        parent = self.parentItem()

        # deduce scale from rectangle
        if (qt.qVersion() < "5.0") or self.keepRatio:
            scalex = self._newRect.rect().width() / self._w
            scaley = scalex
        else:
            scalex = self._newRect.rect().width() / self._w
            scaley = self._newRect.rect().height() / self._h
        if qt.qVersion() < "5.0":
            parent.scale(scalex, scaley)
        else:
            # the correct equivalent would be:
            # rectItem.setTransform(qt.QTransform.fromScale(scalex, scaley))
            parent.setScale(scalex)

        self.scene().removeItem(self._newRect)
        self._newRect = None
        qt.QGraphicsRectItem.mouseReleaseEvent(self, event)
Example #29
0
    def mouseReleaseEvent(self, event):
        point1 = self.pos()
        deltax = point1.x() - self._point0.x()
        deltay = point1.y() - self._point0.y()
        self.moveBy(-deltax, -deltay)
        parent = self.parentItem()

        # deduce scale from rectangle
        if (qt.qVersion() < "5.0") or self.keepRatio:
            scalex = self._newRect.rect().width() / self._w
            scaley = scalex
        else:
            scalex = self._newRect.rect().width() / self._w
            scaley = self._newRect.rect().height() / self._h
        if qt.qVersion() < "5.0":
            parent.scale(scalex, scaley)
        else:
            # the correct equivalent would be:
            # rectItem.setTransform(qt.QTransform.fromScale(scalex, scaley))
            parent.setScale(scalex)

        self.scene().removeItem(self._newRect)
        self._newRect = None
        qt.QGraphicsRectItem.mouseReleaseEvent(self, event)
Example #30
0
 def __sourceChanged(self):
     self.setCheckable(self.__source.isCheckable())
     self.setEnabled(self.__source.isEnabled())
     self.setFont(self.__source.font())
     self.setIcon(self.__source.icon())
     self.setIconText(self.__source.iconText())
     self.setIconVisibleInMenu(self.__source.isIconVisibleInMenu())
     self.setMenuRole(self.__source.menuRole())
     self.setShortcut(self.__source.shortcut())
     self.setShortcutContext(self.__source.shortcutContext())
     if LooseVersion(qt.qVersion()) >= LooseVersion("5.10"):
         self.setShortcutVisibleInContextMenu(self.__source.isShortcutVisibleInContextMenu())
     self.setStatusTip(self.__source.statusTip())
     self.setText(self.__source.text())
     self.setToolTip(self.__source.toolTip())
     self.setVisible(self.__source.isVisible())
     self.setWhatsThis(self.__source.whatsThis())
Example #31
0
    def __rowsAboutToBeRemoved(self, parentIndex, start, end):
        """Called when an item was removed from the model."""
        items = []
        model = self.model()
        for index in range(start, end):
            qindex = model.index(index, 0, parent=parentIndex)
            item = self.__model.itemFromIndex(qindex)
            if isinstance(item, _NxDataItem):
                items.append(item)
        for item in items:
            self.sigNxdataItemRemoved.emit(item)

        if qt.qVersion()[0:2] == "5.":
            # FIXME: workaround for https://github.com/silx-kit/silx/issues/1919
            # Uses of ResizeToContents looks to break nice update of cells with Qt5
            # This patch make the view blinking
            self.repaint()
Example #32
0
    def setData(self, data):
        """Set the h5py-like object exposed by the model

        :param h5pyObject: A h5py-like object. It can be a `h5py.Dataset`,
            a `h5py.File`, a `h5py.Group`. It also can be a,
            `silx.gui.hdf5.H5Node` which is needed to display some local path
            information.
        """
        self.model().setObject(data)
        header = self.horizontalHeader()
        if qt.qVersion() < "5.0":
            setResizeMode = header.setResizeMode
        else:
            setResizeMode = header.setSectionResizeMode
        setResizeMode(0, qt.QHeaderView.Fixed)
        setResizeMode(1, qt.QHeaderView.Stretch)
        header.setStretchLastSection(True)
Example #33
0
 def __sourceChanged(self):
     self.setCheckable(self.__source.isCheckable())
     self.setEnabled(self.__source.isEnabled())
     self.setFont(self.__source.font())
     self.setIcon(self.__source.icon())
     self.setIconText(self.__source.iconText())
     self.setIconVisibleInMenu(self.__source.isIconVisibleInMenu())
     self.setMenuRole(self.__source.menuRole())
     self.setShortcut(self.__source.shortcut())
     self.setShortcutContext(self.__source.shortcutContext())
     if LooseVersion(qt.qVersion()) >= LooseVersion("5.10"):
         self.setShortcutVisibleInContextMenu(
             self.__source.isShortcutVisibleInContextMenu())
     self.setStatusTip(self.__source.statusTip())
     self.setText(self.__source.text())
     self.setToolTip(self.__source.toolTip())
     self.setVisible(self.__source.isVisible())
     self.setWhatsThis(self.__source.whatsThis())
Example #34
0
    def __init__(self, parent=None):
        super(OpenClDeviceDialog, self).__init__(parent)
        filename = get_ui_file("opencl-device-dialog.ui")
        qt.loadUi(filename, self)

        self.__availableIds = {}
        model = self.__createModel()
        self._deviceView.setModel(model)
        self._deviceView.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._deviceView.setSelectionBehavior(qt.QAbstractItemView.SelectRows)

        header = self._deviceView.horizontalHeader()
        if qt.qVersion() < "5.0":
            header.setClickable(True)
            header.setMovable(True)
            header.setSectionResizeMode = self.setResizeMode
        else:
            header.setSectionsClickable(True)
            header.setSectionsMovable(True)
        header.setStretchLastSection(False)
        header.setSectionResizeMode(0, qt.QHeaderView.Stretch)
        header.setSectionResizeMode(1, qt.QHeaderView.Interactive)
        header.setSectionResizeMode(2, qt.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, qt.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(4, qt.QHeaderView.ResizeToContents)

        self._buttonBox.accepted.connect(self.accept)
        self._buttonBox.rejected.connect(self.reject)

        self._group = qt.QButtonGroup(self)
        self._group.setExclusive(True)
        self._group.addButton(self._anyDeviceButton)
        self._group.addButton(self._anyGpuButton)
        self._group.addButton(self._anyCpuButton)
        self._group.addButton(self._availableButton)
        self._group.addButton(self._customButton)
        self._group.buttonClicked.connect(self.__modeChanged)
        self._anyDeviceButton.setChecked(True)
        self.__modeChanged()

        if pyopencl is None:
            self._availableButton.setEnabled(False)
            self._availableButton.setToolTip(
                "PyOpenCL have to be installed to display available devices.")
Example #35
0
    def __init__(self, parent=None, model=None):
        super(TreeView, self).__init__(parent)
        # WARNING : had to set this as a queued connection, otherwise
        # there was a crash after the slot was called (conflict with
        # __setHiddenNodes probably)
        # TODO : investigate
        self.expanded.connect(self.__expanded, Qt.Qt.QueuedConnection)
        self.collapsed.connect(self.__collapsed)

        if int(Qt.qVersion().split('.')[0]) <= 4:
            self.header().setResizeMode(Qt.QHeaderView.ResizeToContents)
        else:
            self.header().setSectionResizeMode(Qt.QHeaderView.ResizeToContents)
        self.__showUniqueGroup = False
        self.__userRoot = False
        # self.setSelectionBehavior(Qt.QAbstractItemView.SelectRows)

        if model:
            self.setModel(model)
Example #36
0
    def setData(self, data):
        """Set the h5py-like object exposed by the model

        :param data: A h5py-like object. It can be a `h5py.Dataset`,
            a `h5py.File`, a `h5py.Group`. It also can be a,
            `silx.gui.hdf5.H5Node` which is needed to display some local path
            information.
        """
        self.model().setObject(data)
        header = self.horizontalHeader()
        if qt.qVersion() < "5.0":
            setResizeMode = header.setResizeMode
        else:
            setResizeMode = header.setSectionResizeMode
        setResizeMode(0, qt.QHeaderView.Fixed)
        setResizeMode(1, qt.QHeaderView.ResizeToContents)
        setResizeMode(2, qt.QHeaderView.Stretch)
        setResizeMode(3, qt.QHeaderView.ResizeToContents)
        setResizeMode(4, qt.QHeaderView.ResizeToContents)
        header.setStretchLastSection(False)
Example #37
0
 def __init__(self, parent=None, scene=None, keepratio=True):
     if qt.qVersion() < '5.0':
         qt.QGraphicsRectItem.__init__(self, parent, scene)
     else:
         qt.QGraphicsRectItem.__init__(self, parent)
     rect = parent.boundingRect()
     x = rect.x()
     y = rect.y()
     w = rect.width()
     h = rect.height()
     self._newRect = None
     self.keepRatio = keepratio
     self.setRect(qt.QRectF(x + w - 40, y + h - 40, 40, 40))
     self.setAcceptHoverEvents(True)
     pen = qt.QPen()
     color = qt.QColor(qt.Qt.white)
     color.setAlpha(0)
     pen.setColor(color)
     pen.setStyle(qt.Qt.NoPen)
     self.setPen(pen)
     self.setBrush(color)
     self.setFlag(self.ItemIsMovable, True)
     self.show()
Example #38
0
 def __init__(self, parent=None, scene=None, keepratio=True):
     if qt.qVersion() < '5.0':
         qt.QGraphicsRectItem.__init__(self, parent, scene)
     else:
         qt.QGraphicsRectItem.__init__(self, parent)
     rect = parent.boundingRect()
     x = rect.x()
     y = rect.y()
     w = rect.width()
     h = rect.height()
     self._newRect = None
     self.keepRatio = keepratio
     self.setRect(qt.QRectF(x + w - 40, y + h - 40, 40, 40))
     self.setAcceptHoverEvents(True)
     pen = qt.QPen()
     color = qt.QColor(qt.Qt.white)
     color.setAlpha(0)
     pen.setColor(color)
     pen.setStyle(qt.Qt.NoPen)
     self.setPen(pen)
     self.setBrush(color)
     self.setFlag(self.ItemIsMovable, True)
     self.show()
Example #39
0
    def configure(self, parsed_options):
        """Configure the TestOptions class from the command line arguments and the
        environment variables
        """
        if not parsed_options.gui:
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "Skipped by command line"
        elif os.environ.get('WITH_QT_TEST', 'True') == 'False':
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "Skipped by WITH_QT_TEST env var"
        elif sys.platform.startswith('linux') and not os.environ.get(
                'DISPLAY', ''):
            self.WITH_QT_TEST = False
            self.WITH_QT_TEST_REASON = "DISPLAY env variable not set"

        if not parsed_options.opencl or os.environ.get('SILX_OPENCL',
                                                       'True') == 'False':
            self.WITH_OPENCL_TEST = False
            # That's an easy way to skip OpenCL tests
            # It disable the use of OpenCL on the full silx project
            os.environ['SILX_OPENCL'] = "False"

        if not parsed_options.opengl:
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "Skipped by command line"
        elif os.environ.get('WITH_GL_TEST', 'True') == 'False':
            self.WITH_GL_TEST = False
            self.WITH_GL_TEST_REASON = "Skipped by WITH_GL_TEST env var"

        if parsed_options.low_mem or os.environ.get('SILX_TEST_LOW_MEM',
                                                    'True') == 'False':
            self.TEST_LOW_MEM = True

        if self.WITH_QT_TEST:
            from silx.gui import qt
            if sys.platform == "win32" and qt.qVersion() == "5.9.2":
                self.SKIP_TEST_FOR_ISSUE_936 = True
Example #40
0
 def mousePressEvent(self, event):
     if self._newRect is not None:
         self._newRect = None
     self._point0 = self.pos()
     parent = self.parentItem()
     scene = self.scene()
     # following line prevents dragging along the previously selected
     # item when resizing another one
     scene.clearSelection()
     rect = parent.rect()
     self._x = rect.x()
     self._y = rect.y()
     self._w = rect.width()
     self._h = rect.height()
     self._ratio = self._w / self._h
     if qt.qVersion() < "5.0":
         self._newRect = qt.QGraphicsRectItem(parent, scene)
     else:
         self._newRect = qt.QGraphicsRectItem(parent)
     self._newRect.setRect(qt.QRectF(self._x,
                                     self._y,
                                     self._w,
                                     self._h))
     qt.QGraphicsRectItem.mousePressEvent(self, event)
Example #41
0
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

from __future__ import absolute_import

__authors__ = ["D. Naudet"]
__license__ = "MIT"
__date__ = "15/09/2016"

import sys

from silx.gui import qt as Qt

print('Using Qt {0}'.format(Qt.qVersion()))

from .XsocsGui import XsocsGui
from .process.MergeWidget import MergeWidget
from .process.QSpaceWidget import QSpaceWidget


def merge_window(*args, **kwargs):
    app = Qt.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    mw = MergeWidget(*args, **kwargs)
    mw.show()
    app.exec_()


def conversion_window(*args, **kwargs):
# 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.
#
# ######################################################################### */
"""Collection of widgets used to build
:class:`silx.gui.fit.FitWidget.FitWidget`"""

from collections import OrderedDict

from silx.gui import qt
from silx.gui.fit.Parameters import Parameters

QTVERSION = qt.qVersion()

__authors__ = ["V.A. Sole", "P. Knobel"]
__license__ = "MIT"
__date__ = "13/10/2016"


class FitActionsButtons(qt.QWidget):
    """Widget with 3 ``QPushButton``:

    The buttons can be accessed as public attributes::

        - ``EstimateButton``
        - ``StartFitButton``
        - ``DismissButton``
Example #43
0
    def addPixmap(self, pixmap, title=None, comment=None, commentPosition=None):
        """Add a pixmap to the print preview scene

        :param QPixmap pixmap: Pixmap to be added to the scene
        :param str title: Title shown above (centered) the pixmap
        :param str comment: Comment displayed below the pixmap
        :param commentPosition: "CENTER" or "LEFT"
        """
        if self._toBeCleared:
            self._clearAll()
        self.ensurePrinterIsSet()
        if self.printer is None:
            _logger.error("printer is not set, cannot add pixmap to page")
            return
        if title is None:
            title = ' ' * 88
        if comment is None:
            comment = ' ' * 88
        if commentPosition is None:
            commentPosition = "CENTER"
        if qt.qVersion() < "5.0":
            rectItem = qt.QGraphicsRectItem(self.page, self.scene)
        else:
            rectItem = qt.QGraphicsRectItem(self.page)

        rectItem.setRect(qt.QRectF(1, 1,
                                   pixmap.width(), pixmap.height()))

        pen = rectItem.pen()
        color = qt.QColor(qt.Qt.red)
        color.setAlpha(1)
        pen.setColor(color)
        rectItem.setPen(pen)
        rectItem.setZValue(1)
        rectItem.setFlag(qt.QGraphicsItem.ItemIsSelectable, True)
        rectItem.setFlag(qt.QGraphicsItem.ItemIsMovable, True)
        rectItem.setFlag(qt.QGraphicsItem.ItemIsFocusable, False)

        rectItemResizeRect = _GraphicsResizeRectItem(rectItem, self.scene)
        rectItemResizeRect.setZValue(2)

        if qt.qVersion() < "5.0":
            pixmapItem = qt.QGraphicsPixmapItem(rectItem, self.scene)
        else:
            pixmapItem = qt.QGraphicsPixmapItem(rectItem)
        pixmapItem.setPixmap(pixmap)
        pixmapItem.setZValue(0)

        # I add the title
        if qt.qVersion() < "5.0":
            textItem = qt.QGraphicsTextItem(title, rectItem, self.scene)
        else:
            textItem = qt.QGraphicsTextItem(title, rectItem)
        textItem.setTextInteractionFlags(qt.Qt.TextEditorInteraction)
        offset = 0.5 * textItem.boundingRect().width()
        textItem.moveBy(0.5 * pixmap.width() - offset, -20)
        textItem.setZValue(2)

        # I add the comment
        if qt.qVersion() < "5.0":
            commentItem = qt.QGraphicsTextItem(comment, rectItem, self.scene)
        else:
            commentItem = qt.QGraphicsTextItem(comment, rectItem)
        commentItem.setTextInteractionFlags(qt.Qt.TextEditorInteraction)
        offset = 0.5 * commentItem.boundingRect().width()
        if commentPosition.upper() == "LEFT":
            x = 1
        else:
            x = 0.5 * pixmap.width() - offset
        commentItem.moveBy(x, pixmap.height() + 20)
        commentItem.setZValue(2)

        rectItem.moveBy(20, 40)
Example #44
0
    def __updateText(self):
        """Update the content of the dialog according to the settings."""
        import silx._version

        message = """<table>
        <tr><td width="50%" align="center" valign="middle">
            <img src="{silx_image_path}" width="100" />
        </td><td width="50%" align="center" valign="middle">
            <b>{application_name}</b>
            <br />
            <br />{silx_version}
            <br />
            <br /><a href="{project_url}">Upstream project on GitHub</a>
        </td></tr>
        </table>
        <dl>
            <dt><b>Silx version</b></dt><dd>{silx_version}</dd>
            <dt><b>Qt version</b></dt><dd>{qt_version}</dd>
            <dt><b>Qt binding</b></dt><dd>{qt_binding}</dd>
            <dt><b>Python version</b></dt><dd>{python_version}</dd>
            <dt><b>Optional libraries</b></dt><dd>{optional_lib}</dd>
        </dl>
        <p>
        Copyright (C) <a href="{esrf_url}">European Synchrotron Radiation Facility</a>
        </p>
        """

        optionals = []
        optionals.append(
            self.__formatOptionalLibraries("H5py", "h5py" in sys.modules))
        optionals.append(
            self.__formatOptionalLibraries("FabIO", "fabio" in sys.modules))

        try:
            import h5py.version
            if h5py.version.hdf5_version_tuple >= (1, 10, 2):
                # Previous versions only return True if the filter was first used
                # to decode a dataset
                import h5py.h5z
                FILTER_LZ4 = 32004
                FILTER_BITSHUFFLE = 32008
                filters = [
                    ("HDF5 LZ4 filter", FILTER_LZ4),
                    ("HDF5 Bitshuffle filter", FILTER_BITSHUFFLE),
                ]
                for name, filterId in filters:
                    isAvailable = h5py.h5z.filter_avail(filterId)
                    optionals.append(
                        self.__formatOptionalFilters(name, isAvailable))
            else:
                optionals.append(
                    self.__formatOptionalLibraries("hdf5plugin", "hdf5plugin"
                                                   in sys.modules))
        except ImportError:
            pass

        # Access to the logo in SVG or PNG
        logo = icons.getQFile("silx:" + os.path.join("gui", "logo", "silx"))

        info = dict(application_name=self.__applicationName,
                    esrf_url="http://www.esrf.eu",
                    project_url="https://github.com/silx-kit/silx",
                    silx_version=silx._version.version,
                    qt_binding=qt.BINDING,
                    qt_version=qt.qVersion(),
                    python_version=sys.version.replace("\n", "<br />"),
                    optional_lib="<br />".join(optionals),
                    silx_image_path=logo.fileName())

        self.__label.setText(message.format(**info))
        self.__updateSize()
Example #45
0
    def addSvgItem(self, item, title=None,
                   comment=None, commentPosition=None,
                   viewBox=None):
        """Add a SVG item to the scene.

        :param QSvgRenderer item: SVG item to be added to the scene.
        :param str title: Title shown above (centered) the SVG item.
        :param str comment: Comment displayed below the SVG item.
        :param str commentPosition: "CENTER" or "LEFT"
        :param QRectF viewBox: Bounding box for the item on the print page
            (xOffset, yOffset, width, height). If None, use original
            item size.
        """
        if not qt.HAS_SVG:
            raise RuntimeError("Missing QtSvg library.")
        if not isinstance(item, qt.QSvgRenderer):
            raise TypeError("addSvgItem: QSvgRenderer expected")
        if self._toBeCleared:
            self._clearAll()
        self.ensurePrinterIsSet()
        if self.printer is None:
            _logger.error("printer is not set, cannot add SvgItem to page")
            return

        if title is None:
            title = 50 * ' '
        if comment is None:
            comment = 80 * ' '
        if commentPosition is None:
            commentPosition = "CENTER"

        if viewBox is None:
            if hasattr(item, "_viewBox"):
                # PyMca compatibility: viewbox attached to item
                viewBox = item._viewBox
            else:
                # try the original item viewbox
                viewBox = item.viewBoxF()

        svgItem = _GraphicsSvgRectItem(viewBox, self.page)
        svgItem.setSvgRenderer(item)

        svgItem.setCacheMode(qt.QGraphicsItem.NoCache)
        svgItem.setZValue(0)
        svgItem.setFlag(qt.QGraphicsItem.ItemIsSelectable, True)
        svgItem.setFlag(qt.QGraphicsItem.ItemIsMovable, True)
        svgItem.setFlag(qt.QGraphicsItem.ItemIsFocusable, False)

        rectItemResizeRect = _GraphicsResizeRectItem(svgItem, self.scene)
        rectItemResizeRect.setZValue(2)

        self._svgItems.append(item)

        if qt.qVersion() < '5.0':
            textItem = qt.QGraphicsTextItem(title, svgItem, self.scene)
        else:
            textItem = qt.QGraphicsTextItem(title, svgItem)
        textItem.setTextInteractionFlags(qt.Qt.TextEditorInteraction)
        title_offset = 0.5 * textItem.boundingRect().width()
        textItem.setZValue(1)
        textItem.setFlag(qt.QGraphicsItem.ItemIsMovable, True)

        dummyComment = 80 * "1"
        if qt.qVersion() < '5.0':
            commentItem = qt.QGraphicsTextItem(dummyComment, svgItem, self.scene)
        else:
            commentItem = qt.QGraphicsTextItem(dummyComment, svgItem)
        commentItem.setTextInteractionFlags(qt.Qt.TextEditorInteraction)
        scaleCalculationRect = qt.QRectF(commentItem.boundingRect())
        scale = svgItem.boundingRect().width() / scaleCalculationRect.width()
        comment_offset = 0.5 * commentItem.boundingRect().width()
        if commentPosition.upper() == "LEFT":
            x = 1
        else:
            x = 0.5 * svgItem.boundingRect().width() - comment_offset * scale  # fixme: centering
        commentItem.moveBy(svgItem.boundingRect().x() + x,
                           svgItem.boundingRect().y() + svgItem.boundingRect().height())
        commentItem.setPlainText(comment)
        commentItem.setZValue(1)

        commentItem.setFlag(qt.QGraphicsItem.ItemIsMovable, True)
        if qt.qVersion() < "5.0":
            commentItem.scale(scale, scale)
        else:
            # the correct equivalent would be:
            # rectItem.setTransform(qt.QTransform.fromScale(scalex, scaley))
            commentItem.setScale(scale)
        textItem.moveBy(svgItem.boundingRect().x() +
                        0.5 * svgItem.boundingRect().width() - title_offset * scale,
                        svgItem.boundingRect().y())
        if qt.qVersion() < "5.0":
            textItem.scale(scale, scale)
        else:
            # the correct equivalent would be:
            # rectItem.setTransform(qt.QTransform.fromScale(scalex, scaley))
            textItem.setScale(scale)
    def setPerspective(self, perspective):
        """Set the perspective by defining a sequence listing all axes
        orthogonal to the frame or 2-D slice to be visualized.

        Alternatively, you can use :meth:`setFrameAxes` for the complementary
        approach of specifying the two axes parallel  to the frame.

        In the 1-D or 2-D case, this parameter is irrelevant.

        In the 3-D case, if the unit vectors describing
        your axes are :math:`\vec{x}, \vec{y}, \vec{z}`, a perspective of 0
        means you slices are parallel to :math:`\vec{y}\vec{z}`, 1 means they
        are parallel to :math:`\vec{x}\vec{z}` and 2 means they
        are parallel to :math:`\vec{x}\vec{y}`.

        In the n-D case, this parameter is a sequence of :math:`n-2` axes
        numbers.
        For instance if you want to display 2-D frames whose axes are the
        second and third dimensions of a 5-D array, set the perspective to
        ``(0, 3, 4)``.

        :param perspective: Sequence of dimensions/axes orthogonal to the
            frames.
        :raise: IndexError if any value in perspective is higher than the
            number of dimensions minus one (first dimension is 0), or
            if the number of values is different from the number of dimensions
            minus two.
        """
        n_dimensions = len(self._array.shape)
        if n_dimensions < 3:
            _logger.warning("perspective is not relevant for 1D and 2D arrays")
            return

        if not hasattr(perspective, "__len__"):
            # we can tolerate an integer for 3-D array
            if n_dimensions == 3:
                perspective = [perspective]
            else:
                raise ValueError("perspective must be a sequence of integers")

        # ensure unicity of dimensions in perspective
        perspective = tuple(set(perspective))

        if len(perspective) != n_dimensions - 2 or\
                min(perspective) < 0 or max(perspective) >= n_dimensions:
            raise IndexError("Invalid perspective " + str(perspective) +
                             " for %d-D array " % n_dimensions +
                             "with shape " + str(self._array.shape))

        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        self._perspective = perspective

        # reset index
        self._index = [0 for _i in range(n_dimensions - 2)]

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #47
0
    def __init__(self, parent=None):
        super(DetectorSelectorDrop, self).__init__(parent)
        qt.loadUi(pyFAI.utils.get_ui_file("detector-selection-drop.ui"), self)

        self.__detector = None
        self.__dialogState = None

        model = self.__createManufacturerModel()
        self._manufacturerList.setModel(model)
        selection = self._manufacturerList.selectionModel()
        selection.selectionChanged.connect(self.__manufacturerChanged)

        model = AllDetectorModel(self)
        modelFilter = DetectorFilter(self)
        modelFilter.setSourceModel(model)

        self._detectorView.setModel(modelFilter)
        self._detectorView.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._detectorView.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
        self._detectorView.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
        self._detectorView.setWordWrap(False)

        header = self._detectorView.horizontalHeader()
        # Manufacturer first
        self.MANUFACTURER_COLUMN = 1
        header.moveSection(self.MANUFACTURER_COLUMN, 0)
        if qt.qVersion() < "5.0":
            header.setSectionResizeMode = self.setResizeMode
        header.setSectionResizeMode(0, qt.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, qt.QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)

        selection = self._detectorView.selectionModel()
        selection.selectionChanged.connect(self.__modelChanged)
        self._detectorView.doubleClicked.connect(self.__selectAndAccept)

        customModel = qt.QStandardItemModel(self)
        item = qt.QStandardItem("From file")
        item.setData("FILE", role=self._CustomDetectorRole)
        customModel.appendRow(item)
        item = qt.QStandardItem("Manual definition")
        item.setData("MANUAL", role=self._CustomDetectorRole)
        customModel.appendRow(item)
        self._customList.setModel(customModel)
        self._customList.setFixedHeight(self._customList.sizeHintForRow(0) * 2)
        selection = self._customList.selectionModel()
        selection.selectionChanged.connect(self.__customSelectionChanged)

        self.__splineFile = DataModel()
        self._splineFile.setModel(self.__splineFile)
        self._splineLoader.clicked.connect(self.loadSplineFile)
        self.__splineFile.changed.connect(self.__splineFileChanged)
        self._splineError.setVisible(False)

        self.__descriptionFile = DataModel()
        self.__descriptionFile.changed.connect(self.__descriptionFileChanged)
        self._fileSelection.setModel(self.__descriptionFile)
        self._fileLoader.clicked.connect(self.__loadDetectorFormFile)
        self._fileResult.setVisible(False)
        self._fileError.setVisible(False)
        self._splinePanel.setVisible(False)

        validator = validators.IntegerAndEmptyValidator()
        validator.setBottom(0)
        self._detectorWidth.setValidator(validator)
        self._detectorHeight.setValidator(validator)

        self.__detectorWidth = DataModel()
        self.__detectorHeight = DataModel()
        self.__pixelWidth = DataModel()
        self.__pixelHeight = DataModel()

        self._detectorWidth.setModel(self.__detectorWidth)
        self._detectorHeight.setModel(self.__detectorHeight)
        self._pixelWidth.setModel(self.__pixelWidth)
        self._pixelHeight.setModel(self.__pixelHeight)

        self._customResult.setVisible(False)
        self._customError.setVisible(False)
        self.__detectorWidth.changed.connect(self.__customDetectorChanged)
        self.__detectorHeight.changed.connect(self.__customDetectorChanged)
        self.__pixelWidth.changed.connect(self.__customDetectorChanged)
        self.__pixelHeight.changed.connect(self.__customDetectorChanged)
        self.__customDetector = None

        # By default select all the manufacturers
        self.__selectAllRegistreredDetector()
    def setArrayData(self, data, copy=True, perspective=None, editable=False):
        """Set the data array and the viewing perspective.

        You can set ``copy=False`` if you need more performances, when dealing
        with a large numpy array. In this case, a simple reference to the data
        is used to access the data, rather than a copy of the array.

        .. warning::

            Any change to the data model will affect your original data
            array, when using a reference rather than a copy..

        :param data: n-dimensional numpy array, or any object that can be
            converted to a numpy array using ``numpy.array(data)`` (e.g.
            a nested sequence).
        :param bool copy: If *True* (default), a copy of the array is stored
            and the original array is not modified if the table is edited.
            If *False*, then the behavior depends on the data type:
            if possible (if the original array is a proper numpy array)
            a reference to the original array is used.
        :param perspective: See documentation of :meth:`setPerspective`.
            If None, the default perspective is the list of the first ``n-2``
            dimensions, to view frames parallel to the last two axes.
        :param bool editable: Flag to enable editing data. Default *False*.
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        if data is None:
            # empty array
            self._array = numpy.array([])
        elif copy:
            # copy requested (default)
            self._array = numpy.array(data, copy=True)
            if hasattr(data, "dtype"):
                # Avoid to lose the monkey-patched h5py dtype
                self._array.dtype = data.dtype
        elif not _is_array(data):
            raise TypeError("data is not a proper array. Try setting" +
                            " copy=True to convert it into a numpy array" +
                            " (this will cause the data to be copied!)")
            # # copy not requested, but necessary
            # _logger.warning(
            #         "data is not an array-like object. " +
            #         "Data must be copied.")
            # self._array = numpy.array(data, copy=True)
        else:
            # Copy explicitly disabled & data implements required attributes.
            # We can use a reference.
            self._array = data

        # reset colors to None if new data shape is inconsistent
        valid_color_shapes = (self._array.shape + (3, ),
                              self._array.shape + (4, ))
        if self._bgcolors is not None:
            if self._bgcolors.shape not in valid_color_shapes:
                self._bgcolors = None
        if self._fgcolors is not None:
            if self._fgcolors.shape not in valid_color_shapes:
                self._fgcolors = None

        self.setEditable(editable)

        self._index = [0 for _i in range((len(self._array.shape) - 2))]
        self._perspective = tuple(perspective) if perspective is not None else\
            tuple(range(0, len(self._array.shape) - 2))

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #49
0
    def setPerspective(self, perspective):
        """Set the perspective by defining a sequence listing all axes
        orthogonal to the frame or 2-D slice to be visualized.

        Alternatively, you can use :meth:`setFrameAxes` for the complementary
        approach of specifying the two axes parallel  to the frame.

        In the 1-D or 2-D case, this parameter is irrelevant.

        In the 3-D case, if the unit vectors describing
        your axes are :math:`\vec{x}, \vec{y}, \vec{z}`, a perspective of 0
        means you slices are parallel to :math:`\vec{y}\vec{z}`, 1 means they
        are parallel to :math:`\vec{x}\vec{z}` and 2 means they
        are parallel to :math:`\vec{x}\vec{y}`.

        In the n-D case, this parameter is a sequence of :math:`n-2` axes
        numbers.
        For instance if you want to display 2-D frames whose axes are the
        second and third dimensions of a 5-D array, set the perspective to
        ``(0, 3, 4)``.

        :param perspective: Sequence of dimensions/axes orthogonal to the
            frames.
        :raise: IndexError if any value in perspective is higher than the
            number of dimensions minus one (first dimension is 0), or
            if the number of values is different from the number of dimensions
            minus two.
        """
        n_dimensions = len(self._array.shape)
        if n_dimensions < 3:
            _logger.warning(
                    "perspective is not relevant for 1D and 2D arrays")
            return

        if not hasattr(perspective, "__len__"):
            # we can tolerate an integer for 3-D array
            if n_dimensions == 3:
                perspective = [perspective]
            else:
                raise ValueError("perspective must be a sequence of integers")

        # ensure unicity of dimensions in perspective
        perspective = tuple(set(perspective))

        if len(perspective) != n_dimensions - 2 or\
                min(perspective) < 0 or max(perspective) >= n_dimensions:
            raise IndexError(
                    "Invalid perspective " + str(perspective) +
                    " for %d-D array " % n_dimensions +
                    "with shape " + str(self._array.shape))

        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        self._perspective = perspective

        # reset index
        self._index = [0 for _i in range(n_dimensions - 2)]

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #50
0
    def __init__(self, parent=None):
        super(DetectorSelectorDrop, self).__init__(parent)
        qt.loadUi(pyFAI.utils.get_ui_file("detector-selection-drop.ui"), self)

        self.__detector = None
        self.__dialogState = None

        model = self.__createManufacturerModel()
        self._manufacturerList.setModel(model)
        selection = self._manufacturerList.selectionModel()
        selection.selectionChanged.connect(self.__manufacturerChanged)

        model = AllDetectorModel(self)
        modelFilter = DetectorFilter(self)
        modelFilter.setSourceModel(model)

        self._detectorView.setModel(modelFilter)
        self._detectorView.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._detectorView.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
        self._detectorView.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
        self._detectorView.setWordWrap(False)

        header = self._detectorView.horizontalHeader()
        # Manufacturer first
        self.MANUFACTURER_COLUMN = 1
        header.moveSection(self.MANUFACTURER_COLUMN, 0)
        if qt.qVersion() < "5.0":
            header.setSectionResizeMode = self.setResizeMode
        header.setSectionResizeMode(0, qt.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, qt.QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)

        selection = self._detectorView.selectionModel()
        selection.selectionChanged.connect(self.__modelChanged)
        self._detectorView.doubleClicked.connect(self.__selectAndAccept)

        customModel = qt.QStandardItemModel(self)
        item = qt.QStandardItem("From file")
        item.setData("FILE", role=self._CustomDetectorRole)
        customModel.appendRow(item)
        item = qt.QStandardItem("Manual definition")
        item.setData("MANUAL", role=self._CustomDetectorRole)
        customModel.appendRow(item)
        self._customList.setModel(customModel)
        self._customList.setFixedHeight(self._customList.sizeHintForRow(0) * 2)
        selection = self._customList.selectionModel()
        selection.selectionChanged.connect(self.__customSelectionChanged)

        self.__splineFile = DataModel()
        self._splineFile.setModel(self.__splineFile)
        self._splineLoader.clicked.connect(self.loadSplineFile)
        self.__splineFile.changed.connect(self.__splineFileChanged)
        self._splineError.setVisible(False)

        self.__descriptionFile = DataModel()
        self.__descriptionFile.changed.connect(self.__descriptionFileChanged)
        self._fileSelection.setModel(self.__descriptionFile)
        self._fileLoader.clicked.connect(self.__loadDetectorFormFile)
        self._fileResult.setVisible(False)
        self._fileError.setVisible(False)
        self._splinePanel.setVisible(False)

        validator = validators.IntegerAndEmptyValidator()
        validator.setBottom(0)
        self._detectorWidth.setValidator(validator)
        self._detectorHeight.setValidator(validator)

        self.__detectorWidth = DataModel()
        self.__detectorHeight = DataModel()
        self.__pixelWidth = DataModel()
        self.__pixelHeight = DataModel()

        self._detectorWidth.setModel(self.__detectorWidth)
        self._detectorHeight.setModel(self.__detectorHeight)
        self._pixelWidth.setModel(self.__pixelWidth)
        self._pixelHeight.setModel(self.__pixelHeight)

        self._customResult.setVisible(False)
        self._customError.setVisible(False)
        self.__detectorWidth.changed.connect(self.__customDetectorChanged)
        self.__detectorHeight.changed.connect(self.__customDetectorChanged)
        self.__pixelWidth.changed.connect(self.__customDetectorChanged)
        self.__pixelHeight.changed.connect(self.__customDetectorChanged)
        self.__customDetector = None

        # By default select all the manufacturers
        self.__selectAllRegistreredDetector()
Example #51
0
    def setArrayData(self, data, copy=True,
                     perspective=None, editable=False):
        """Set the data array and the viewing perspective.

        You can set ``copy=False`` if you need more performances, when dealing
        with a large numpy array. In this case, a simple reference to the data
        is used to access the data, rather than a copy of the array.

        .. warning::

            Any change to the data model will affect your original data
            array, when using a reference rather than a copy..

        :param data: n-dimensional numpy array, or any object that can be
            converted to a numpy array using ``numpy.array(data)`` (e.g.
            a nested sequence).
        :param bool copy: If *True* (default), a copy of the array is stored
            and the original array is not modified if the table is edited.
            If *False*, then the behavior depends on the data type:
            if possible (if the original array is a proper numpy array)
            a reference to the original array is used.
        :param perspective: See documentation of :meth:`setPerspective`.
            If None, the default perspective is the list of the first ``n-2``
            dimensions, to view frames parallel to the last two axes.
        :param bool editable: Flag to enable editing data. Default *False*.
        """
        if qt.qVersion() > "4.6":
            self.beginResetModel()
        else:
            self.reset()

        if data is None:
            # empty array
            self._array = numpy.array([])
        elif copy:
            # copy requested (default)
            self._array = numpy.array(data, copy=True)
            if hasattr(data, "dtype"):
                # Avoid to lose the monkey-patched h5py dtype
                self._array.dtype = data.dtype
        elif not _is_array(data):
            raise TypeError("data is not a proper array. Try setting" +
                            " copy=True to convert it into a numpy array" +
                            " (this will cause the data to be copied!)")
            # # copy not requested, but necessary
            # _logger.warning(
            #         "data is not an array-like object. " +
            #         "Data must be copied.")
            # self._array = numpy.array(data, copy=True)
        else:
            # Copy explicitly disabled & data implements required attributes.
            # We can use a reference.
            self._array = data

        # reset colors to None if new data shape is inconsistent
        valid_color_shapes = (self._array.shape + (3,),
                              self._array.shape + (4,))
        if self._bgcolors is not None:
            if self._bgcolors.shape not in valid_color_shapes:
                self._bgcolors = None
        if self._fgcolors is not None:
            if self._fgcolors.shape not in valid_color_shapes:
                self._fgcolors = None

        self.setEditable(editable)

        self._index = [0 for _i in range((len(self._array.shape) - 2))]
        self._perspective = tuple(perspective) if perspective is not None else\
            tuple(range(0, len(self._array.shape) - 2))

        if qt.qVersion() > "4.6":
            self.endResetModel()
Example #52
0
 def __rowsAboutToBeInserted(self, parentIndex, start, end):
     if qt.qVersion()[0:2] == "5.":
         # FIXME: workaround for https://github.com/silx-kit/silx/issues/1919
         # Uses of ResizeToContents looks to break nice update of cells with Qt5
         # This patch make the view blinking
         self.repaint()
        self.assertEqual(tableItems['coords min'].text(), '0, 2')
        self.assertEqual(tableItems['max'].text(), '90')
        self.assertEqual(tableItems['coords max'].text(), '50, 69')
        self.assertEqual(tableItems['delta'].text(), '85')


class TestEmptyStatsWidget(TestCaseQt):
    def test(self):
        widget = StatsWidget.StatsWidget()
        widget.show()
        self.qWaitForWindowExposed(widget)


# skip unit test for pyqt4 because there is some unrealised widget without
# apparent reason
@unittest.skipIf(qt.qVersion().split('.')[0] == '4', reason='PyQt4 not tested')
class TestLineWidget(TestCaseQt):
    """Some test for the StatsLineWidget."""
    def setUp(self):
        TestCaseQt.setUp(self)

        mystats = statshandler.StatsHandler(
            ((stats.StatMin(), statshandler.StatFormatter()), ))

        self.plot = Plot1D()
        self.plot.show()
        x = range(20)
        y = range(20)
        self.plot.addCurve(x, y, legend='curve0')
        y = range(12, 32)
        self.plot.addCurve(x, y, legend='curve1')
Example #54
0
__date__ = "15/02/2017"

import logging
import sys
import traceback
import warnings

from silx.math.fit import fittheories
from silx.math.fit import fitmanager, functions
from silx.gui import qt
from .FitWidgets import (FitActionsButtons, FitStatusLines,
                         FitConfigWidget, ParametersTab)
from .FitConfig import getFitConfigDialog
from .BackgroundWidget import getBgDialog, BackgroundDialog

QTVERSION = qt.qVersion()
DEBUG = 0
_logger = logging.getLogger(__name__)


__authors__ = ["V.A. Sole", "P. Knobel"]
__license__ = "MIT"
__date__ = "30/11/2016"


class FitWidget(qt.QWidget):
    """This widget can be used to configure, run and display results of a
    fitting process.

    The standard steps for using this widget is to initialize it, then load
    the data to be fitted.
Example #55
0
    def __updateText(self):
        """Update the content of the dialog according to the settings."""
        import silx._version

        message = """<table>
        <tr><td width="50%" align="center" valign="middle">
            <img src="{silx_image_path}" width="100" />
        </td><td width="50%" align="center" valign="middle">
            <b>{application_name}</b>
            <br />
            <br />{silx_version}
            <br />
            <br /><a href="{project_url}">Upstream project on GitHub</a>
        </td></tr>
        </table>
        <dl>
            <dt><b>Silx version</b></dt><dd>{silx_version}</dd>
            <dt><b>Qt version</b></dt><dd>{qt_version}</dd>
            <dt><b>Qt binding</b></dt><dd>{qt_binding}</dd>
            <dt><b>Python version</b></dt><dd>{python_version}</dd>
            <dt><b>Optional libraries</b></dt><dd>{optional_lib}</dd>
        </dl>
        <p>
        Copyright (C) <a href="{esrf_url}">European Synchrotron Radiation Facility</a>
        </p>
        """

        optionals = []
        optionals.append(self.__formatOptionalLibraries("H5py", "h5py" in sys.modules))
        optionals.append(self.__formatOptionalLibraries("FabIO", "fabio" in sys.modules))

        try:
            import h5py.version
            if h5py.version.hdf5_version_tuple >= (1, 10, 2):
                # Previous versions only return True if the filter was first used
                # to decode a dataset
                import h5py.h5z
                FILTER_LZ4 = 32004
                FILTER_BITSHUFFLE = 32008
                filters = [
                    ("HDF5 LZ4 filter", FILTER_LZ4),
                    ("HDF5 Bitshuffle filter", FILTER_BITSHUFFLE),
                ]
                for name, filterId in filters:
                    isAvailable = h5py.h5z.filter_avail(filterId)
                    optionals.append(self.__formatOptionalFilters(name, isAvailable))
            else:
                optionals.append(self.__formatOptionalLibraries("hdf5plugin", "hdf5plugin" in sys.modules))
        except ImportError:
            pass

        # Access to the logo in SVG or PNG
        logo = icons.getQFile("../logo/silx")

        info = dict(
            application_name=self.__applicationName,
            esrf_url="http://www.esrf.eu",
            project_url="https://github.com/silx-kit/silx",
            silx_version=silx._version.version,
            qt_binding=qt.BINDING,
            qt_version=qt.qVersion(),
            python_version=sys.version.replace("\n", "<br />"),
            optional_lib="<br />".join(optionals),
            silx_image_path=logo.fileName()
        )

        self.__label.setText(message.format(**info))
        self.__updateSize()