예제 #1
0
    def __updateItemsFromModel(self, codeList, model, method):
        for name in codeList:
            index = self.__indexFromCode(model, name)
            if not index.isValid():
                continue
            item = model.itemFromIndex(index)

            localMethod = tuple(name if m is None else m for m in method)
            methods = method_registry.IntegrationMethod.select_method(
                1, *localMethod, degradable=False)
            available1d = len(methods) != 0
            methods = method_registry.IntegrationMethod.select_method(
                2, *localMethod, degradable=False)
            available2d = len(methods) != 0

            label = self._HUMAN_READABLE.get(name, name)
            if available1d and available2d:
                color = qt.Qt.black
            elif not available1d and not available2d:
                color = qt.Qt.gray
            else:
                color = qt.Qt.red
                if available1d:
                    label = "%s (only 1D)" % label
                elif available2d:
                    label = "%s (only 2D)" % label

            item.setForeground(qt.QBrush(color))
            item.setText(label)
예제 #2
0
    def highlight(self, item):
        font = qt.QFont("Verdana")
        font.setBold(True)
        item.setFont(font)

        brush = qt.QBrush(qt.Qt.red)
        item.setForeground(brush)
예제 #3
0
    def paint(self, painter, option, index):
        txt = index.model().data(index, qt.Qt.DisplayRole)
        if txt == '':
            return
        if txt.startswith('no'):
            super(SymbolDelegate, self).paint(painter, option, index)
            return
        lineSymbol = lineSymbols[lineSymbolsText[txt]]
        painter.save()
        painter.setRenderHint(qt.QPainter.Antialiasing, True)
        rect = option.rect
        rect.adjust(+5, 0, -5, 0)

        symbolFC = qt.QColor(self.parent().color)
        symbolEC = qt.QColor(self.parent().color)
        # symbolSize = self.parent().sizeSpinBox.value() * 2
        symbolSize = (self.parent().sizeSpinBox.value() + 1) * 1.75
        symbolPath = qt.QPainterPath(lineSymbol)
        scale = symbolSize
        painter.scale(scale, scale)
        symbolOffset = qt.QPointF(
            (rect.left() + rect.right() - symbolSize) * 0.5 / scale,
            (rect.top() + rect.bottom() - symbolSize) * 0.5 / scale)
        symbolPath.translate(symbolOffset)
        symbolBrush = qt.QBrush(symbolFC, qt.Qt.SolidPattern)
        symbolPen = qt.QPen(symbolEC, 1. / scale, qt.Qt.SolidLine)
        painter.setPen(symbolPen)
        painter.setBrush(symbolBrush)
        painter.drawPath(symbolPath)
        painter.restore()
예제 #4
0
    def setProfile(self, x, y, colormap):
        """

        :param profile: a 1D numpy array
        :param colormap: an XsocsPlot2DColormap instance
        :param nColors: number of colors
        :return:
        """
        assert x.ndim == 1
        assert y.ndim == 1

        self.__colormap = colormap
        self.__pixmap = pixmap = Qt.QPixmap(Qt.QSize(x.size,
                                                     self._pimapHeight))
        pixmap.fill()

        xMin = x.min()
        xMax = x.max()

        colors = _applyColormap(colormap, x)
        profileValues = (y * (1.0 * self._pimapHeight / y.max()))
        points = [Qt.QPointF(0, 0)]
        points.extend(
            [Qt.QPointF(idx, val) for idx, val in enumerate(profileValues)])
        points.extend([Qt.QPointF(colormap.nColors - 1, 0)])
        poly = Qt.QPolygonF(points)

        if colormap.minVal is not None:
            lineMin = ((colormap.minVal - xMin) * (pixmap.width() - 1) /
                       (xMax - xMin))
        else:
            lineMin = None

        if colormap.maxVal is not None:
            lineMax = ((colormap.maxVal - xMin) * (pixmap.width() - 1) /
                       (xMax - xMin))
        else:
            lineMax = None

        self.__lineMin = lineMin
        self.__lineMax = lineMax

        gradient = Qt.QLinearGradient(Qt.QPoint(0, 0),
                                      Qt.QPoint(colormap.nColors - 1, 0))
        for idx, color in enumerate(colors):
            qColor = Qt.QColor.fromRgbF(*color)
            gradient.setColorAt(idx / (1.0 * (colormap.nColors - 1)), qColor)

        painter = Qt.QPainter(pixmap)
        painter.save()
        painter.scale(1, -1.)
        painter.translate(Qt.QPointF(0., -1.0 * self._pimapHeight))
        brush = Qt.QBrush(gradient)
        painter.setBrush(brush)
        painter.setPen(Qt.QPen(Qt.Qt.NoPen))
        painter.drawPolygon(poly)
        painter.restore()
        painter.end()
        self.update()
예제 #5
0
 def hoverEnterEvent(self, event):
     if self.parentItem().isSelected():
         self.parentItem().setSelected(False)
     if self.keepRatio:
         self.setCursor(qt.QCursor(qt.Qt.SizeFDiagCursor))
     else:
         self.setCursor(qt.QCursor(qt.Qt.SizeAllCursor))
     self.setBrush(qt.QBrush(qt.Qt.yellow, qt.Qt.SolidPattern))
     return qt.QGraphicsRectItem.hoverEnterEvent(self, event)
예제 #6
0
 def __setBrush(self):
     """Selected cells are yellow when not current.
     The current cell is dark yellow when selected or grey when not
     selected.
     Other cells have no bg color by default, unless specified at
     instantiation (:attr:`bgcolor`)"""
     palette = self.palette()
     # if self.current and self.selected:
     #     self.brush = qt.QBrush(self.selected_current_color)
     # el
     if self.selected:
         self.brush = qt.QBrush(self.selected_color)
     # elif self.current:
     #     self.brush = qt.QBrush(self.current_color)
     elif self.bgcolor is not None:
         self.brush = qt.QBrush(self.bgcolor)
     else:
         self.brush = qt.QBrush()
     palette.setBrush(self.backgroundRole(), self.brush)
     self.setPalette(palette)
     self.update()
예제 #7
0
 def paintCheckBox(self, painter, rect):
     for coords in [self.coords1, self.coords2]:
         pointerPath = qt.QPainterPath()
         pointerPath.moveTo(*coords[0])
         for xy in coords[1:]:
             if isinstance(xy, tuple):
                 pointerPath.lineTo(*xy)
             if isinstance(xy, type('')):
                 end = xy.split(',')
                 if end[0] == 'close':
                     pointerPath.closeSubpath()
                 symbolPen = qt.QPen(qt.Qt.black, float(end[1].strip()))
         symbolBrush = qt.QBrush(qt.Qt.white)
         painter.setPen(symbolPen)
         painter.setBrush(symbolBrush)
         pointerPath.translate(rect.x() + 12, rect.y() + 16)
         painter.drawPath(pointerPath)
예제 #8
0
    def __init__(self, item, parent=None):
        """

        :param parent: Parent widget
        :param PeriodicTableItem item: :class:`PeriodicTableItem` object
        """
        qt.QPushButton.__init__(self, parent)

        self.item = item
        """:class:`PeriodicTableItem` object represented by this button"""

        self.setText(item.symbol)
        self.setFlat(1)
        self.setCheckable(0)

        self.setSizePolicy(
            qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding))

        self.selected = False
        self.current = False

        # selection colors
        self.selected_color = qt.QColor(qt.Qt.yellow)
        self.current_color = qt.QColor(qt.Qt.gray)
        self.selected_current_color = qt.QColor(qt.Qt.darkYellow)

        # element colors

        if hasattr(item, "bgcolor"):
            self.bgcolor = qt.QColor(item.bgcolor)
        else:
            self.bgcolor = qt.QColor("#FFFFFF")

        self.brush = qt.QBrush()
        self.__setBrush()

        self.clicked.connect(self.clickedSlot)
예제 #9
0
    def __updateItemsFromModel(self, codeList, model, method, patch):
        for name in codeList:
            index = self.__indexFromCode(model, name)
            if not index.isValid():
                continue
            item = model.itemFromIndex(index)

            if patch == "algo":
                localMethod = method.fixed(algo=name)
            elif patch == "impl":
                localMethod = method.fixed(impl=name)
            elif patch == "split":
                localMethod = method.fixed(split=name)

            localMethod = localMethod.fixed(dim=1)
            methods = method_registry.IntegrationMethod.select_method(
                method=localMethod, degradable=False)
            available1d = len(methods) != 0
            localMethod = localMethod.fixed(dim=2)
            methods = method_registry.IntegrationMethod.select_method(
                method=localMethod, degradable=False)
            available2d = len(methods) != 0

            label = self._HUMAN_READABLE.get(name, name)
            if available1d and available2d:
                color = qt.Qt.black
            elif not available1d and not available2d:
                color = qt.Qt.gray
            else:
                color = qt.Qt.red
                if available1d:
                    label = "%s (only 1D)" % label
                elif available2d:
                    label = "%s (only 2D)" % label

            item.setForeground(qt.QBrush(color))
            item.setText(label)
예제 #10
0
    def paintEvent(self, e):
        txt = self.currentText()
        if txt == '':
            return
        if txt.startswith('no'):
            super(SymbolComboBox, self).paintEvent(e)
            return
        lineSymbol = lineSymbols[lineSymbolsText[txt]]
        p = qt.QStylePainter(self)
        p.setPen(self.palette().color(qt.QPalette.Text))
        opt = qt.QStyleOptionComboBox()
        self.initStyleOption(opt)
        p.drawComplexControl(qt.QStyle.CC_ComboBox, opt)
        painter = qt.QPainter(self)
        painter.save()
        painter.setRenderHint(qt.QPainter.Antialiasing, True)
        rect = p.style().subElementRect(qt.QStyle.SE_ComboBoxFocusRect, opt,
                                        self)
        rect.adjust(+5, 0, -5, 0)

        symbolFC = qt.QColor(self.parent().color)
        symbolEC = qt.QColor(self.parent().color)
        symbolSize = self.parent().sizeSpinBox.value() * 2
        symbolPath = qt.QPainterPath(lineSymbol)
        scale = symbolSize
        painter.scale(scale, scale)
        symbolOffset = qt.QPointF(
            (rect.left() + rect.right() - symbolSize) * 0.5 / scale,
            (rect.top() + rect.bottom() - symbolSize) * 0.5 / scale)
        symbolPath.translate(symbolOffset)
        symbolBrush = qt.QBrush(symbolFC, qt.Qt.SolidPattern)
        symbolPen = qt.QPen(symbolEC, 1. / scale, qt.Qt.SolidLine)
        painter.setPen(symbolPen)
        painter.setBrush(symbolBrush)
        painter.drawPath(symbolPath)
        painter.restore()
예제 #11
0
    def paintEvent(self, event):
        painter = Qt.QPainter(self)

        style = Qt.QApplication.style()

        area = self.__drawArea()
        pixmapRect = self.__pixMapRect()

        sliders = self.__sliders

        option = Qt.QStyleOptionProgressBar()
        option.initFrom(self)
        option.rect = area
        option.state = ((self.isEnabled() and Qt.QStyle.State_Enabled)
                        or Qt.QStyle.State_None)
        style.drawControl(Qt.QStyle.CE_ProgressBarGroove, option, painter,
                          self)

        # showing interval rect only if show is forced or if there is not
        # background and show is True or None
        showRngBckgrnd = (self.__showRangeBackground
                          or (self.__pixmap and self.__showRangeBackground)
                          or (self.__pixmap is None
                              and self.__showRangeBackground is None)
                          or self.__showRangeBackground)

        alpha = (self.isEnabled() and 255) or 100

        if showRngBckgrnd:
            painter.save()
            rect = Qt.QRect(area)
            rect.setLeft(sliders['left'].center().x())
            rect.setRight(sliders['right'].center().x())
            gradient = Qt.QLinearGradient(area.topLeft(), area.bottomLeft())
            color = Qt.QColor(Qt.Qt.cyan)
            color.setAlpha(alpha)
            gradient.setColorAt(0., color)
            color = Qt.QColor(Qt.Qt.blue)
            color.setAlpha(alpha)
            gradient.setColorAt(1., color)
            brush = Qt.QBrush(gradient)
            painter.setBrush(brush)
            painter.drawRect(rect)
            painter.restore()

        if self.__pixmap and alpha == 255:
            painter.save()
            pen = painter.pen()
            pen.setWidth(2)
            pen.setColor(Qt.Qt.black)
            painter.setPen(pen)
            painter.drawRect(pixmapRect.adjusted(-1, -1, 1, 1))
            painter.restore()

            painter.drawPixmap(
                area.adjusted(self._sliderWidth / 2, self._pixmapVOffset,
                              -self._sliderWidth / 2, -self._pixmapVOffset),
                self.__pixmap, self.__pixmap.rect())

        option = Qt.QStyleOptionButton()
        option.initFrom(self)

        for side, slider in sliders.items():
            option.icon = self.__sliderIcons[side]
            option.iconSize = slider.size() * 0.7
            if self.__hover == side:
                option.state |= Qt.QStyle.State_MouseOver
            elif option.state & Qt.QStyle.State_MouseOver:
                option.state ^= Qt.QStyle.State_MouseOver
            if self.__focus == side:
                option.state |= Qt.QStyle.State_HasFocus
            elif option.state & Qt.QStyle.State_HasFocus:
                option.state ^= Qt.QStyle.State_HasFocus
            option.rect = slider
            style.drawControl(Qt.QStyle.CE_PushButton, option, painter, self)
예제 #12
0
    def setProjectFile(self, projectFile):
        view = self.findChild(Qt.QTreeWidget)

        view.clear()

        self.__valid = False

        if projectFile is None:
            return

        errMsg = ''

        try:
            # reading project file
            errMsg = 'Failed to open X-Socs project file.'
            projectH5 = XsocsProject(projectFile, mode='r')

            # reading XSOCS data file
            errMsg = 'Failed to open X-Socs data file.'
            xsocsFile = projectH5.xsocsFile
            xsocsH5 = XsocsH5(xsocsFile, mode='r')

            # getting entries
            errMsg = 'Failed to read entries from data file.'
            entries = xsocsH5.entries()

            # getting entries
            errMsg = 'Failed to read scan parameters.'
            params = xsocsH5.scan_params(entries[0])

            inputItem = Qt.QTreeWidgetItem(
                ['Data file', os.path.basename(xsocsFile)])
            inputItem.setToolTip(0, xsocsFile)
            inputItem.setToolTip(1, xsocsFile)
            inputItem.addChild(Qt.QTreeWidgetItem(['Full path', xsocsFile]))
            view.addTopLevelItem(inputItem)

            # getting scan angles
            errMsg = 'Failed to read scan angles.'
            # TODO : check that there are at least 2 angles
            text = '{0} [{1} -> {2}]'.format(
                str(len(entries)), str(xsocsH5.scan_angle(entries[0])),
                str(xsocsH5.scan_angle(entries[-1])))
            entriesItem = Qt.QTreeWidgetItem(['Angles', text])
            for entryIdx, entry in enumerate(entries):
                text = 'eta = {0}'.format(str(xsocsH5.scan_angle(entry)))
                entryItem = Qt.QTreeWidgetItem([str(entryIdx), text])
                entriesItem.addChild(entryItem)
            view.addTopLevelItem(entriesItem)

            # getting acquisition params
            errMsg = 'Failed to read Acquisition parameters.'
            title = ' '.join(str(value) for value in params.values())
            commandItem = Qt.QTreeWidgetItem(['Scan', title])
            commandItem.setToolTip(0, title)
            commandItem.setToolTip(1, title)
            for key, value in params.items():
                commandItem.addChild(Qt.QTreeWidgetItem([key, str(value)]))
            view.addTopLevelItem(commandItem)

            for key, value in xsocsH5.acquisition_params(entries[0]).items():
                view.addTopLevelItem(Qt.QTreeWidgetItem([key, str(value)]))

        except Exception as ex:
            style = Qt.QApplication.style()
            errorItem = Qt.QTreeWidgetItem(['', errMsg])
            icon = style.standardIcon(Qt.QStyle.SP_MessageBoxCritical)
            errorItem.setIcon(0, icon)
            errorItem.setBackground(1, Qt.QBrush(Qt.Qt.red))
            exItem = Qt.QTreeWidgetItem([ex.__class__.__name__, str(ex)])
            errorItem.addChild(exItem)
            view.addTopLevelItem(errorItem)
            errorItem.setExpanded(True)
            return

        self.__valid = True
예제 #13
0
    def paint(self, painter, option, index):
        data = index.data(qt.Qt.DisplayRole)
        if data is None:
            return
        bknd = index.data(qt.Qt.BackgroundRole)

        rect = option.rect
        painter.save()
        painter.setRenderHint(qt.QPainter.Antialiasing, False)
        painter.setPen(qt.Qt.NoPen)
        if ((option.state & qt.QStyle.State_Selected
             or option.state & qt.QStyle.State_MouseOver)) and bknd not in [
                 BAD_BKGND, UNDEFINED_BKGND, NOTFOUND_BKGND, MATHERROR_BKGND
             ]:
            color = self.parent().palette().highlight().color()
            color.setAlphaF(0.1)
        else:
            color = bknd
        if color is not None:
            painter.setBrush(color)
        painter.drawRect(rect)

        if (type(data) is tuple and bknd not in [
                BAD_BKGND, UNDEFINED_BKGND, NOTFOUND_BKGND, MATHERROR_BKGND
        ]):  # plot props
            lineColor = qt.QColor(data[0])
            lineProps = data[1]
            lineWidth = (lineProps.get('linewidth', 1) + 0.5)
            lineStyle = lineStyles[lineProps.get('linestyle', '-')]

            if lineStyle == qt.Qt.NoPen:
                painter.setPen(qt.QPen(qt.Qt.lightGray))
                painter.drawText(option.rect, qt.Qt.AlignCenter, "hidden")
            else:
                axisY = lineProps.get('yaxis', -1)
                if isinstance(axisY, type("")):
                    axisY = -1 if axisY.startswith("l") else 1


#                line
                linePen = qt.QPen(qt.QBrush(lineColor), lineWidth, lineStyle,
                                  qt.Qt.FlatCap)
                painter.setPen(linePen)
                linePath = qt.QPainterPath()
                if axisY == -1:  # forbid left arrow, comment out to allow it
                    axisY = 0
                dl = lineWidth if axisY == -1 else 0
                dr = lineWidth if axisY == 1 else 0
                linePath.moveTo(rect.left() + 3 + dl,
                                (rect.top() + rect.bottom()) * 0.5)
                linePath.lineTo(rect.right() - 3 - dr,
                                (rect.top() + rect.bottom()) * 0.5)
                painter.drawPath(linePath)

                #                 > or < symbol
                font = painter.font()
                font.setFamily("Arial")
                font.setPointSize(4 + lineWidth)
                painter.setFont(font)

                dh = 2
                rect.setBottom(rect.bottom() - dh)
                if axisY == -1:
                    painter.drawText(rect,
                                     qt.Qt.AlignLeft | qt.Qt.AlignVCenter,
                                     LEFT_SYMBOL)
                elif axisY == 1:
                    painter.drawText(rect,
                                     qt.Qt.AlignRight | qt.Qt.AlignVCenter,
                                     RIGHT_SYMBOL)
                rect.setBottom(rect.bottom() + dh)

            symbol = lineProps.get('symbol', None)
            if symbol in noSymbols:
                symbol = None
            if symbol:
                painter.setRenderHint(qt.QPainter.Antialiasing, True)
                #                symbolFC = lineProps.get(
                #                    'fc', lineProps.get('facecolor', qt.Qt.black))
                #                symbolEC = lineProps.get(
                #                    'ec', lineProps.get('edgecolor', qt.Qt.black))
                symbolFC = lineColor
                symbolEC = lineColor
                symbolSize = (lineProps.get('symbolsize', 2) + 1) * 1.75
                symbolPath = qt.QPainterPath(lineSymbols[symbol])

                scale = symbolSize
                painter.scale(scale, scale)
                symbolOffset = qt.QPointF(
                    (rect.left() + rect.right() - symbolSize) * 0.5 / scale,
                    (rect.top() + rect.bottom() - symbolSize) * 0.5 / scale)
                symbolPath.translate(symbolOffset)
                symbolBrush = qt.QBrush(symbolFC, qt.Qt.SolidPattern)
                # symbolPen = qt.QPen(symbolEC, 1./scale, qt.Qt.SolidLine)
                symbolPen = qt.QPen(symbolEC, 0, qt.Qt.SolidLine)

                painter.setPen(symbolPen)
                painter.setBrush(symbolBrush)
                painter.drawPath(symbolPath)
        elif type(data) is not tuple:
            if isinstance(data, int):
                painter.setPen(qt.QPen(qt.Qt.lightGray))
            else:
                painter.setPen(qt.QPen(qt.Qt.black))
            font = painter.font()
            # font.setFamily("Arial")
            # font.setPointSize(10)
            painter.setFont(font)
            painter.drawText(option.rect, qt.Qt.AlignCenter,
                             "{0}".format(data))
        elif bknd == UNDEFINED_BKGND:
            painter.setPen(qt.QPen(qt.Qt.darkGray))
            font = painter.font()
            painter.setFont(font)
            painter.drawText(option.rect, qt.Qt.AlignCenter, "out")
        elif bknd == MATHERROR_BKGND:
            painter.setPen(qt.QPen(qt.Qt.red))
            font = painter.font()
            painter.setFont(font)
            painter.drawText(option.rect, qt.Qt.AlignCenter, "error")
        elif bknd == NOTFOUND_BKGND:
            painter.setPen(qt.QPen(qt.Qt.red))
            font = painter.font()
            painter.setFont(font)
            painter.drawText(option.rect, qt.Qt.AlignCenter, "not found")
        painter.restore()