Exemplo n.º 1
0
    def createIconFromSvg(self, svg, color=None, colorsToBeReplaced=None):
        """ Creates a QIcon given an SVG string.

            Optionally replaces the colors in colorsToBeReplaced by color.

            :param svg: string containing Scalable Vector Graphics XML
            :param color: '#RRGGBB' string (e.g. '#FF0000' for red)
            :param colorsToBeReplaced: optional list of colors to be replaced by color
                If None, it will be set to the fill colors of the snip-icon libary
            :return: QtGui.QIcon
        """
        if colorsToBeReplaced is None:
            colorsToBeReplaced = self.colorsToBeReplaced

        if color:
            for oldColor in colorsToBeReplaced:
                svg = svg.replace(oldColor, color)

        # From http://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt
        qByteArray = QtCore.QByteArray()
        qByteArray.append(svg)
        svgRenderer = QtSvg.QSvgRenderer(qByteArray)
        icon = QtGui.QIcon()
        for size in self.renderSizes:
            pixMap = QtGui.QPixmap(QtCore.QSize(size, size))
            pixMap.fill(Qt.transparent)
            pixPainter = QtGui.QPainter(pixMap)
            pixPainter.setRenderHint(QtGui.QPainter.TextAntialiasing, True)
            pixPainter.setRenderHint(QtGui.QPainter.Antialiasing, True)
            svgRenderer.render(pixPainter)
            pixPainter.end()
            icon.addPixmap(pixMap)

        return icon
Exemplo n.º 2
0
    def createPlotDataItem(self):
        """ Creates a PyQtGraph PlotDataItem from the config values
        """
        antialias = self.antiAliasCti.configValue

        color = self.penColor
        if self.lineCti.configValue:
            pen = QtGui.QPen()
            pen.setCosmetic(True)
            pen.setColor(color)
            pen.setWidthF(self.lineWidthCti.configValue)
            pen.setStyle(self.lineStyleCti.configValue)
            shadowCti = self.lineCti.findByNodePath('shadow')
            shadowPen = shadowCti.createPen(altStyle=pen.style(),
                                            altWidth=2.0 * pen.widthF())
        else:
            pen = None
            shadowPen = None

        drawSymbols = self.symbolCti.configValue
        symbolShape = self.symbolShapeCti.configValue if drawSymbols else None
        symbolSize = self.symbolSizeCti.configValue if drawSymbols else 0.0
        symbolPen = None  # otherwise the symbols will also have dotted/solid line.
        symbolBrush = QtGui.QBrush(color) if drawSymbols else None

        plotDataItem = pg.PlotDataItem(antialias=antialias,
                                       pen=pen,
                                       shadowPen=shadowPen,
                                       symbol=symbolShape,
                                       symbolSize=symbolSize,
                                       symbolPen=symbolPen,
                                       symbolBrush=symbolBrush)
        return plotDataItem
Exemplo n.º 3
0
    def testColorCti(self):

        colorStr = '#FF33EE'
        cti = ColorCti('color', defaultData=colorStr)
        self.assertEqual(cti.data, QtGui.QColor(colorStr))
        self.assertEqual(cti.data, QtGui.QColor(colorStr))
        self.assertEqual(cti.displayValue, colorStr)
Exemplo n.º 4
0
class MainGroupCti(GroupCti):
    """ Read only config Tree Item that only stores None.
        To be used as a high level group (e.g. the inspector group)
        Is the same as a groupCti but drawn as light text on a dark grey back ground
    """
    _backgroundBrush = QtGui.QBrush(
        QtGui.QColor("#606060"))  # create only once
    _foregroundBrush = QtGui.QBrush(QtGui.QColor(Qt.white))  # create only once
    _font = QtGui.QFont()
    _font.setWeight(QtGui.QFont.Bold)

    def __init__(self, nodeName, defaultData=None):
        """ Constructor. For the parameters see the AbstractCti constructor documentation.
        """
        super(MainGroupCti, self).__init__(nodeName,
                                           defaultData,
                                           expanded=True)  # always expand

    @property
    def font(self):
        """ Returns a font for displaying this item's text in the tree.
        """
        return self._font

    @property
    def backgroundBrush(self):
        """ Returns a (dark gray) brush for drawing the background role in the tree.
        """
        return self._backgroundBrush

    @property
    def foregroundBrush(self):
        """ Returns a (white) brush for drawing the foreground role in the tree.
        """
        return self._foregroundBrush
Exemplo n.º 5
0
    def __init__(self, tableModel=None, parent=None):
        """ Constructor.
        """
        super(TableEditWidget, self).__init__(parent=parent)

        self.setFocusPolicy(Qt.NoFocus)

        self.mainLayout = QtWidgets.QHBoxLayout()
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.mainLayout)

        self.tableView = BaseTableView(tableModel)
        self.mainLayout.addWidget(self.tableView)

        buttonLayout = QtWidgets.QVBoxLayout()
        self.mainLayout.addLayout(buttonLayout)

        iconDir = icons_directory()
        iconSize = QtCore.QSize(20, 20)

        self.addButton = QtWidgets.QPushButton()
        self.addButton.setToolTip("Add new row.")
        self.addButton.setIcon(
            QtGui.QIcon(os.path.join(iconDir, 'plus-sign-l.svg')))
        self.addButton.setIconSize(iconSize)
        self.addButton.clicked.connect(self.addRow)
        buttonLayout.addWidget(self.addButton)

        self.removeButton = QtWidgets.QPushButton()
        self.removeButton.setToolTip("Remove row.")
        self.removeButton.setIcon(
            QtGui.QIcon(os.path.join(iconDir, 'minus-sign-l.svg')))
        self.removeButton.setIconSize(iconSize)
        self.removeButton.clicked.connect(self.removeRow)
        buttonLayout.addWidget(self.removeButton)
        buttonLayout.addSpacing(25)

        self.moveUpButton = QtWidgets.QPushButton()
        self.moveUpButton.setToolTip("Move row up")
        self.moveUpButton.setIcon(
            QtGui.QIcon(os.path.join(iconDir, 'circle-arrow-up-l.svg')))
        self.moveUpButton.setIconSize(iconSize)
        self.moveUpButton.clicked.connect(lambda: self.moveRow(-1))
        buttonLayout.addWidget(self.moveUpButton)

        self.moveDownButton = QtWidgets.QPushButton()
        self.moveDownButton.setToolTip("Move row down")
        self.moveDownButton.setIcon(
            QtGui.QIcon(os.path.join(iconDir, 'circle-arrow-down-l.svg')))
        self.moveDownButton.setIconSize(iconSize)
        self.moveDownButton.clicked.connect(lambda: self.moveRow(+1))
        buttonLayout.addWidget(self.moveDownButton)

        buttonLayout.addStretch()

        self.tableView.selectionModel().currentChanged.connect(
            self.onCurrentChanged)
        self.tableView.setFocus(Qt.NoFocusReason)
        self.updateWidgets()
Exemplo n.º 6
0
    def __init__(self, store, parent=None):
        """ Constructor.

            :param store: Underlying data store, must descent from BaseRegistry
            :param parent: Parent widget
        """
        super(BaseRegistryModel, self).__init__(store, parent)
        check_class(store, BaseRegistry)

        self.regularBrush = QtGui.QBrush(QCOLOR_REGULAR)
        self.notImportedBrush = QtGui.QBrush(QCOLOR_NOT_IMPORTED)
        self.errorBrush = QtGui.QBrush(QCOLOR_ERROR)
Exemplo n.º 7
0
class TestFileRti(BaseRti):
    """ Repository tree item for testing
    """
    _label = "HDF File"
    _iconOpen = QtGui.QIcon(
        os.path.join(ICONS_DIRECTORY, 'memory.folder-open.svg'))
    _iconClosed = QtGui.QIcon(
        os.path.join(ICONS_DIRECTORY, 'memory.folder-closed.svg'))

    def __init__(self, nodeName='', fileName=''):
        """ Constructor
        """
        super(TestFileRti, self).__init__(nodeName=nodeName, fileName=fileName)
        self._checkFileExists()
Exemplo n.º 8
0
    def __init__(self, registry, attrNames = ('fullName', ), parent=None):
        """ Constructor.

            :param registry: Underlying registry. Must descent from ClassRegistry
            :param attrNames: List of attributes that will be displayed (def. only the fullName).
            :param parent: Parent widget
        """
        super(RegistryTableModel, self).__init__(parent)
        check_class(registry, ClassRegistry)
        self.registry = registry
        self.attrNames = attrNames

        self.regularBrush = QtGui.QBrush(QCOLOR_REGULAR)
        self.notImportedBrush = QtGui.QBrush(QCOLOR_NOT_IMPORTED)
        self.errorBrush = QtGui.QBrush(QCOLOR_ERROR)
Exemplo n.º 9
0
    def __init__(self, textInspector, nodeName):
        """ Constructor

            :param textInspector: the TextInspector widget that is being configured
            :param nodeName: node name
        """
        super(TextInspectorCti, self).__init__(nodeName)

        check_class(textInspector, TextInspector)
        self.textInspector = textInspector

        Opt = QtGui.QTextOption
        self.wordWrapCti = self.insertChild(
            ChoiceCti('word wrap',
                      displayValues=[
                          'No wrapping', 'Word boundaries', 'Anywhere',
                          'Boundaries or anywhere'
                      ],
                      configValues=[
                          Opt.NoWrap, Opt.WordWrap, Opt.WrapAnywhere,
                          Opt.WrapAtWordBoundaryOrAnywhere
                      ]))

        self.encodingCti = self.insertChild(
            ChoiceCti(
                'encoding',
                editable=True,
                configValues=['utf-8', 'ascii', 'latin-1', 'windows-1252']))

        self.fontCti = self.insertChild(
            FontCti(self.textInspector.editor,
                    "font",
                    defaultData=QtGui.QFont(MONO_FONT, FONT_SIZE)))
Exemplo n.º 10
0
    def _drawContents(self, reason=None, initiator=None):
        """ Draws the plot contents from the sliced array of the collected repo tree item.

            The reason parameter is used to determine if the axes will be reset (the initiator
            parameter is ignored). See AbstractInspector.updateContents for their description.
        """
        self.slicedArray = self.collector.getSlicedArray()

        if not self._hasValidData():
            self._clearContents()
            raise InvalidDataError(
                "No data available or it does not contain real numbers")

        # -- Valid plot data from here on --

        # PyQtGraph doesn't handle masked arrays so we convert the masked values to Nans (missing
        # data values are replaced by NaNs). The PyQtGraph line plot omits the Nans, which is great.
        self.slicedArray.replaceMaskedValueWithNan(
        )  # will convert data to float if int

        self.plotItem.clear()

        # Reset the axes ranges (via the config)
        if (reason == UpdateReason.RTI_CHANGED
                or reason == UpdateReason.COLLECTOR_COMBO_BOX):

            # self.config.yAxisRangeCti.setAutoRangeOn() doesn't work as refreshBlocked is True
            # TODO: can refreshBlocked maybe only block the signals to prevent loops?
            self.config.xAxisRangeCti.autoRangeCti.data = True
            self.config.yAxisRangeCti.autoRangeCti.data = True

        self.titleLabel.setText(
            self.configValue('title').format(**self.collector.rtiInfo))

        connected = np.isfinite(self.slicedArray.data)
        if is_an_array(self.slicedArray.mask):
            connected = np.logical_and(connected, ~self.slicedArray.mask)
        else:
            connected = np.zeros_like(
                self.slicedArray.data) if self.slicedArray.mask else connected

        plotDataItem = self.config.plotDataItemCti.createPlotDataItem()
        plotDataItem.setData(self.slicedArray.data, connect=connected)

        self.plotItem.addItem(plotDataItem)

        if self.config.probeCti.configValue:
            self.probeLabel.setVisible(True)
            self.plotItem.addItem(self.crossLineVerShadow, ignoreBounds=True)
            self.plotItem.addItem(self.crossLineVertical, ignoreBounds=True)
            self.plotItem.addItem(self.probeDataItem, ignoreBounds=True)
            self.probeDataItem.setSymbolBrush(
                QtGui.QBrush(self.config.plotDataItemCti.penColor))
            self.probeDataItem.setSymbolSize(10)
        else:
            self.probeLabel.setVisible(False)

        # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector,
        # e.g. the axis range may have changed while drawing.
        self.config.updateTarget()
Exemplo n.º 11
0
 def _enforceDataType(self, data):
     """ Converts to str so that this CTI always stores that type.
     """
     qColor = QtGui.QColor(data)    # TODO: store a RGB string?
     if not qColor.isValid():
         raise ValueError("Invalid color specification: {!r}".format(data))
     return qColor
Exemplo n.º 12
0
    def _updateWidgets(self):
        """ Updates the combo and spin boxes given the new rti or axes.
            Emits the sigContentsChanged signal.
        """
        row = 0
        model = self.tree.model()

        # Create path label
        nodePath = '' if self.rti is None else self.rti.nodePath
        pathItem = model.item(row, 0)
        if pathItem:
            # Reusing path item. If we remove all items the column size will be lost.
            pathItem.setText(nodePath)
        else:
            pathItem = QtGui.QStandardItem(nodePath)
            pathItem.setEditable(False)
            model.setItem(row, 0, pathItem)

        pathItem.setToolTip(nodePath)
        if self.rti is not None:
            pathItem.setIcon(self.rti.decoration)

        self._deleteSpinBoxes(row)
        self._populateComboBoxes(row)
        self._createSpinBoxes(row)
        self._updateRtiInfo()

        self.tree.resizeColumnsFromContents(startCol=self.COL_FIRST_COMBO)

        logger.debug("{} sigContentsChanged signal (_updateWidgets)".format(
            "Blocked" if self.signalsBlocked() else "Emitting"))
        self.sigContentsChanged.emit(UpdateReason.RTI_CHANGED)
Exemplo n.º 13
0
    def __init__(self, nodeName, defaultData, resetTo=None, expanded=True,
                 includeNoneStyle=False, includeZeroWidth=False):
        """ Sets the children's default value using the resetTo value.

            The resetTo value must be a QPen or value that can be converted to QPen. It is used
            to initialize the child nodes' defaultValues. If resetTo is None, the default QPen
            will be used, which is a black solid pen of width 1.0.

            (resetTo is not called 'defaultData' since the PenCti itself always has a data and
            defaultData of None. That is, it does not store the data itself but relies on its
            child nodes). The default data, is used to indicate if the pen is enabled.

            If includeNonStyle is True, an None-option will be prepended to the style choice
        """
        super(PenCti, self).__init__(nodeName, defaultData, expanded=expanded,
                                     childrenDisabledValue=False)
        # We don't need a similar initFrom parameter.
        qPen = QtGui.QPen(resetTo)

        self.colorCti = self.insertChild(ColorCti('color', defaultData=qPen.color()))
        defaultIndex = PEN_STYLE_CONFIG_VALUES.index(qPen.style()) + int(includeNoneStyle)
        self.styleCti = self.insertChild(createPenStyleCti('style', defaultData=defaultIndex,
                                                           includeNone=includeNoneStyle))
        self.widthCti = self.insertChild(createPenWidthCti('width', defaultData=qPen.widthF(),
                                                zeroValueText=' ' if includeZeroWidth else None))
Exemplo n.º 14
0
    def __init__(self, parent=None, msg="", title="Error"):
        super(MessageDisplay, self).__init__(parent=parent)

        self.layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.layout)

        self.titleLabel = QtWidgets.QLabel(title)
        self.titleLabel.setTextFormat(Qt.PlainText)
        self.titleLabel.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.titleLabel.setAlignment(Qt.AlignHCenter)
        self.layout.addWidget(self.titleLabel, stretch=0)

        font = QtGui.QFont()
        font.setFamily(MONO_FONT)
        font.setFixedPitch(True)
        font.setPointSize(FONT_SIZE)

        self.messageLabel = QtWidgets.QLabel(msg)
        self.messageLabel.setFont(font)
        self.messageLabel.setTextFormat(Qt.PlainText)
        self.messageLabel.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.messageLabel.setWordWrap(True)
        self.messageLabel.setAlignment(Qt.AlignTop)
        self.messageLabel.setFrameStyle(QtWidgets.QFrame.Panel
                                        | QtWidgets.QFrame.Plain)
        self.layout.addWidget(self.messageLabel, stretch=1)
Exemplo n.º 15
0
    def __init__(self, targetWidget, nodeName='font', defaultData=None):
        """ Constructor.

            :param targetWidget: a QWidget that must have a setFont() method
            For the (other) parameters see the AbstractCti constructor documentation.
        """
        super(FontCti, self).__init__(nodeName,
                                defaultData=QtGui.QFont() if defaultData is None else defaultData)

        self._targetWidget = targetWidget

        self.familyCti = self.insertChild(
            FontChoiceCti("family", defaultFamily=self.defaultData.family()))

        self.pointSizeCti = self.insertChild(
            IntCti("size", self.defaultData.pointSize(),
                   minValue=1, maxValue=500, stepSize=1, suffix=' pt'))

        QtF = QtGui.QFont
        weights = [QtF.Light, QtF.Normal, QtF.DemiBold, QtF.Bold, QtF.Black]
        self.weightCti = self.insertChild(
            ChoiceCti("weight", defaultData=fontWeightIndex(self.defaultData, weights),
                      displayValues=['Light', 'Normal', 'DemiBold', 'Bold', 'Black'],
                      configValues=weights))

        self.italicCti = self.insertChild(BoolCti("italic", self.defaultData.italic()))
Exemplo n.º 16
0
    def __createInspectorActionGroup(self, parent):
        """ Creates an action group with 'set inspector' actions for all installed inspector.
        """
        actionGroup = QtWidgets.QActionGroup(parent)
        actionGroup.setExclusive(True)

        sortedItems = sorted(self.argosApplication.inspectorRegistry.items,
                             key=lambda item: item.identifier)
        shortCutNr = 1
        for item in sortedItems:
            logger.debug("item: {}".format(item.identifier))
            setAndDrawFn = partial(self.setAndDrawInspectorById,
                                   item.identifier)
            action = QtWidgets.QAction(item.name,
                                       self,
                                       triggered=setAndDrawFn,
                                       checkable=True)
            action.setData(item.identifier)
            if shortCutNr <= 9 and "debug" not in item.identifier:  # TODO: make configurable by the user
                action.setShortcut(
                    QtGui.QKeySequence("Ctrl+{}".format(shortCutNr)))
                shortCutNr += 1

            actionGroup.addAction(action)

        return actionGroup
Exemplo n.º 17
0
    def _createConfig(self):
        """ Creates a config tree item (CTI) hierarchy containing default children.
        """
        rootItem = MainGroupCti('debug inspector')

        if DEBUGGING:
            # Some test config items.
            import numpy as np
            from argos.config.untypedcti import UntypedCti
            from argos.config.stringcti import StringCti
            from argos.config.intcti import IntCti
            from argos.config.floatcti import FloatCti, SnFloatCti
            from argos.config.boolcti import BoolCti, BoolGroupCti
            from argos.config.choicecti import ChoiceCti
            from argos.config.qtctis import PenCti

            grpItem = GroupCti("group")
            rootItem.insertChild(grpItem)

            lcItem = UntypedCti('line color', 123)
            grpItem.insertChild(lcItem)

            disabledItem = rootItem.insertChild(StringCti('disabled', "Can't touch me"))
            disabledItem.enabled=False

            grpItem.insertChild(IntCti('line-1 color', 7, minValue = -5, stepSize=2,
                                       prefix="@", suffix="%", specialValueText="I'm special"))
            rootItem.insertChild(StringCti('letter', 'aa', maxLength = 1))
            grpItem.insertChild(FloatCti('width', 2, minValue =5, stepSize=0.45, decimals=3,
                                         prefix="@", suffix="%", specialValueText="so very special"))
            grpItem.insertChild(SnFloatCti('scientific', defaultData=-np.inf))

            gridItem = rootItem.insertChild(BoolGroupCti('grid', True))
            gridItem.insertChild(BoolCti('X-Axis', True))
            gridItem.insertChild(BoolCti('Y-Axis', False))

            rootItem.insertChild(ChoiceCti('hobbit', 2, editable=True,
                                           configValues=['Frodo', 'Sam', 'Pippin', 'Merry']))
            myPen = QtGui.QPen(QtGui.QColor('#1C8857'))
            myPen.setWidth(2)
            myPen.setStyle(Qt.DashDotDotLine)
            rootItem.insertChild(PenCti('line', False, resetTo=myPen))

        return rootItem
Exemplo n.º 18
0
 def paintEvent(self, event):
     """ Reimplementation of paintEvent to allow for style sheets
         See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget
     """
     opt = QtWidgets.QStyleOption()
     opt.initFrom(self)
     painter = QtGui.QPainter(self)
     self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, painter,
                                self)
     painter.end()
Exemplo n.º 19
0
 def _setHeaderLabel(self, col, text):
     """ Sets the header of column col to text.
         Will increase the number of columns if col is larger than the current number.
     """
     model = self.tree.model()
     item = model.horizontalHeaderItem(col)
     if item:
         item.setText(text)
     else:
         model.setHorizontalHeaderItem(col, QtGui.QStandardItem(text))
Exemplo n.º 20
0
 def _nodeUnmarshall(self, data):
     """ Initializes itself non-recursively from data. Is called by unmarshall()
     """
     qFont = QtGui.QFont()
     success = qFont.fromString(data)
     if not success:
         msg = "Unable to create QFont from string {!r}".format(data)
         logger.warning(msg)
         if DEBUGGING:
             raise ValueError(msg)
     self.data = qFont
Exemplo n.º 21
0
    def __init__(self, nodeName="pen", defaultData=None, expanded=True):
        """ Constructor.
        """
        super(PgPlotDataItemCti, self).__init__(nodeName,
                                                defaultData=defaultData,
                                                expanded=expanded)
        self.antiAliasCti = self.insertChild(BoolCti("anti-alias", True))

        self.colorCti = self.insertChild(
            ColorCti('color', QtGui.QColor('#FF0066')))
        self.lineCti = self.insertChild(
            BoolCti('line', True, expanded=False, childrenDisabledValue=False))
        self.lineStyleCti = self.lineCti.insertChild(
            createPenStyleCti('style'))
        self.lineWidthCti = self.lineCti.insertChild(
            createPenWidthCti('width'))

        defaultShadowPen = QtGui.QPen(QtGui.QColor('#BFBFBF'))
        defaultShadowPen.setWidth(0)
        self.lineCti.insertChild(
            PenCti("shadow",
                   False,
                   expanded=False,
                   resetTo=QtGui.QPen(defaultShadowPen),
                   includeNoneStyle=True,
                   includeZeroWidth=True))

        self.symbolCti = self.insertChild(
            BoolCti("symbol",
                    False,
                    expanded=False,
                    childrenDisabledValue=False))
        self.symbolShapeCti = self.symbolCti.insertChild(
            ChoiceCti("shape",
                      0,
                      displayValues=[
                          'circle', 'square', 'triangle', 'diamond', 'plus'
                      ],
                      configValues=['o', 's', 't', 'd', '+']))
        self.symbolSizeCti = self.symbolCti.insertChild(
            IntCti('size', 5, minValue=0, maxValue=100, stepSize=1))
Exemplo n.º 22
0
 def _nodeSetValuesFromDict(self, dct):
     """ Sets values from a dictionary in the current node.
         Non-recursive auxiliary function for setValuesFromDict
     """
     if 'data' in dct:
         qFont = QtGui.QFont()
         success = qFont.fromString(dct['data'])
         if not success:
             msg = "Unable to create QFont from string {!r}".format(dct['data'])
             logger.warn(msg)
             if DEBUGGING:
                 raise ValueError(msg)
         self.data = qFont
Exemplo n.º 23
0
    def openColorDialog(self):
        """ Opens a QColorDialog for the user
        """
        try:
            currentColor = self.getData()
        except InvalidInputError:
            currentColor = "#FFFFFF"

        qColor = QtWidgets.QColorDialog.getColor(QtGui.QColor(currentColor),
                                                 self)

        if qColor.isValid():
            self.setData(qColor)
Exemplo n.º 24
0
    def __createInspectorActionGroup(self, parent):
        """ Creates an action group with 'set inspector' actions for all installed inspector.
        """
        actionGroup = QtWidgets.QActionGroup(parent)
        actionGroup.setExclusive(True)

        for item in self.argosApplication.inspectorRegistry.items:
            logger.debug("__createInspectorActionGroup item: {} {}".format(item.identifier, item._data))
            setAndDrawFn = partial(self.setAndDrawInspectorById, item.identifier)
            action = QtWidgets.QAction(item.name, self, triggered=setAndDrawFn, checkable=True)
            action.setData(item.identifier)
            if item.shortCut:
                try:
                    keySeq = QtGui.QKeySequence(item.shortCut.strip())
                except Exception as ex:
                    logger.warning("Unable to create short cut from: '{}".format(item.shortCut))
                else:
                    action.setShortcut(QtGui.QKeySequence(keySeq))

            actionGroup.addAction(action)

        return actionGroup
Exemplo n.º 25
0
    def _updateTargetFromNode(self):
        """ Applies the font config settings to the target widget's font.

            That is the targetWidget.setFont() is called with a font create from the config values.
        """
        font = self.data
        if self.familyCti.configValue:
            font.setFamily(self.familyCti.configValue)
        else:
            font.setFamily(QtGui.QFont().family()) # default family
        font.setPointSize(self.pointSizeCti.configValue)
        font.setWeight(self.weightCti.configValue)
        font.setItalic(self.italicCti.configValue)
        self._targetWidget.setFont(font)
Exemplo n.º 26
0
 def configValue(self):
     """ Creates a QPen made of the children's config values.
     """
     if not self.data:
         return None
     else:
         pen = QtGui.QPen()
         pen.setCosmetic(True)
         pen.setColor(self.colorCti.configValue)
         style = self.styleCti.configValue
         if style is not None:
             pen.setStyle(style)
         pen.setWidthF(self.widthCti.configValue)
         return pen
Exemplo n.º 27
0
    def getData(self):
        """ Gets data from the editor widget.
        """
        text = self.lineEditor.text()
        if not text.startswith('#'):
            text = '#' + text

        validator = self.lineEditor.validator()
        if validator is not None:
            state, text, _ = validator.validate(text, 0)
            if state != QtGui.QValidator.Acceptable:
                raise InvalidInputError("Invalid input: {!r}".format(text))

        return  QtGui.QColor(text)
Exemplo n.º 28
0
    def __init__(self, cti, delegate, subEditors=None, parent=None):
        """ Wraps the child widgets in a horizontal layout and appends a reset button.

            Maintains a reference to the ConfigTreeItem (cti) and to delegate, this last reference
            is so that we can command the delegate to commit and close the editor.

            The subEditors must be a list of QWidgets. Note that the sub editors do not yet have
            to be initialized with editor data since setData will be called by the delegate
            after construction. There it can be taken care of.
        """
        super(AbstractCtiEditor, self).__init__(parent=parent)

        # Prevent underlying table cell from being visible if the editor doesn't fill the cell
        self.setAutoFillBackground(True)

        self._subEditors = []
        self.delegate = delegate
        self.cti = cti

        # From the QAbstractItemDelegate.createEditor docs: The returned editor widget should have
        # Qt.StrongFocus; otherwise, QMouseEvents received by the widget will propagate to the view.
        # The view's background will shine through unless the editor paints its own background
        # (e.g., with setAutoFillBackground()).
        self.setFocusPolicy(Qt.StrongFocus)

        self.hBoxLayout = QtWidgets.QHBoxLayout()
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.setSpacing(0)
        self.setLayout(self.hBoxLayout)

        self.resetButton = QtWidgets.QToolButton()
        self.resetButton.setText("Reset")
        self.resetButton.setToolTip("Reset to default value.")
        self.resetButton.setIcon(
            QtGui.QIcon(os.path.join(icons_directory(), 'reset-l.svg')))
        self.resetButton.setFocusPolicy(Qt.NoFocus)
        self.resetButton.clicked.connect(self.resetEditorValue)
        self.hBoxLayout.addWidget(self.resetButton, alignment=Qt.AlignRight)

        self.cti.model.sigItemChanged.connect(self.modelItemChanged)

        for subEditor in (subEditors if subEditors is not None else []):
            self.addSubEditor(subEditor)
Exemplo n.º 29
0
    def __init__(self, cti, delegate, parent=None):
        """ See the AbstractCtiEditor for more info on the parameters
        """
        super(ColorCtiEditor, self).__init__(cti, delegate, parent=parent)

        lineEditor = QtWidgets.QLineEdit(parent)
        regExp = QtCore.QRegExp(r'#?[0-9A-F]{6}', Qt.CaseInsensitive)
        validator = QtGui.QRegExpValidator(regExp, parent=lineEditor)
        lineEditor.setValidator(validator)

        self.lineEditor = self.addSubEditor(lineEditor, isFocusProxy=True)

        pickButton = QtWidgets.QToolButton()
        pickButton.setText("...")
        pickButton.setToolTip("Open color dialog.")
        pickButton.setFocusPolicy(Qt.NoFocus)
        pickButton.clicked.connect(self.openColorDialog)

        self.pickButton = self.addSubEditor(pickButton)
Exemplo n.º 30
0
    def __init__(self, parent):
        """ Constructor
        """
        super(CollectorTree, self).__init__(parent=parent)

        self._comboLabels = None

        nCols = 1
        model = QtGui.QStandardItemModel(3, nCols)
        self.setModel(model)
        self.setTextElideMode(
            Qt.ElideMiddle)  # ellipsis appear in the middle of the text

        self.setRootIsDecorated(False)  # disable expand/collapse triangle
        self.setUniformRowHeights(True)

        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
        self.setHorizontalScrollMode(
            QtWidgets.QAbstractItemView.ScrollPerPixel)
        self.setAnimated(True)
        self.setAllColumnsShowFocus(True)
        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.setIconSize(COLLECTOR_TREE_ICON_SIZE)

        treeHeader = self.header()
        treeHeader.setStretchLastSection(False)
        treeHeader.setSectionsMovable(False)

        treeHeader.resizeSection(0, 600)  # For item path
        treeHeader.setSectionResizeMode(
            QtWidgets.QHeaderView.Interactive)  # don't set to stretch

        labels = [''] * model.columnCount()
        labels[0] = "Path"
        model.setHorizontalHeaderLabels(labels)