コード例 #1
0
    def overlay_text(
        self,
        message: str,
        color: int,
        size: int,
        x: int,
        y: int,
        timeout: int,
        font_name: str,
        centered: bool,
        shadow: bool,
    ):
        gfx = QGraphicsTextItem(message)
        gfx.setDefaultTextColor(decode_color(color))

        font = QFont(font_name, min(50, size))
        font.setStyleHint(QFont.SansSerif)
        gfx.setFont(font)

        if shadow:
            effect = QGraphicsDropShadowEffect(gfx)
            effect.setBlurRadius(0)
            effect.setColor(Qt.GlobalColor.black)
            effect.setOffset(1, 1)
            gfx.setGraphicsEffect(effect)

        if centered:
            # The provided x, y is at the center of the text
            bound = gfx.boundingRect()
            gfx.setPos(x - (bound.width() / 2), y - (bound.height() / 2))
        else:
            gfx.setPos(x, y)

        self._finalize_gfx(gfx, timeout)
コード例 #2
0
class NodeItem(AbstractNodeItem):
    """
    Base Node item.

    Args:
        name (str): name displayed on the node.
        parent (QtWidgets.QGraphicsItem): parent item.
    """
    def __init__(self, name='node', parent=None):
        super(NodeItem, self).__init__(name, parent)
        pixmap = QtGui.QPixmap(ICON_NODE_BASE)
        if pixmap.size().height() > NODE_ICON_SIZE:
            pixmap = pixmap.scaledToHeight(NODE_ICON_SIZE,
                                           QtCore.Qt.SmoothTransformation)
        self._properties['icon'] = ICON_NODE_BASE
        self._icon_item = QGraphicsPixmapItem(pixmap, self)
        self._icon_item.setTransformationMode(QtCore.Qt.SmoothTransformation)
        self._text_item = QGraphicsTextItem(self.name, self)
        self._x_item = XDisabledItem(self, 'DISABLED')
        self._input_items = {}
        self._output_items = {}
        self._widgets = {}

    def paint(self, painter, option, widget):
        """
        Draws the node base not the ports.

        Args:
            painter (QtGui.QPainter): painter used for drawing the item.
            option (QtGui.QStyleOptionGraphicsItem):
                used to describe the parameters needed to draw.
            widget (QtWidgets.QWidget): not used.
        """
        painter.save()
        bg_border = 1.0
        rect = QtCore.QRectF(0.5 - (bg_border / 2), 0.5 - (bg_border / 2),
                             self._width + bg_border, self._height + bg_border)
        radius = 2
        border_color = QtGui.QColor(*self.border_color)

        path = QtGui.QPainterPath()
        path.addRoundedRect(rect, radius, radius)
        painter.setPen(QtGui.QPen(border_color.darker(200), 1.5))
        painter.drawPath(path)

        rect = self.boundingRect()
        bg_color = QtGui.QColor(*self.color)
        painter.setBrush(bg_color)
        painter.setPen(QtCore.Qt.NoPen)
        painter.drawRoundRect(rect, radius, radius)

        if self.selected and NODE_SEL_COLOR:
            painter.setBrush(QtGui.QColor(*NODE_SEL_COLOR))
            painter.drawRoundRect(rect, radius, radius)

        label_rect = QtCore.QRectF(rect.left() + (radius / 2),
                                   rect.top() + (radius / 2),
                                   self._width - (radius / 1.25), 28)
        path = QtGui.QPainterPath()
        path.addRoundedRect(label_rect, radius / 1.5, radius / 1.5)
        painter.setBrush(QtGui.QColor(0, 0, 0, 50))
        painter.fillPath(path, painter.brush())

        border_width = 0.8
        if self.selected and NODE_SEL_BORDER_COLOR:
            border_width = 1.2
            border_color = QtGui.QColor(*NODE_SEL_BORDER_COLOR)
        border_rect = QtCore.QRectF(rect.left() - (border_width / 2),
                                    rect.top() - (border_width / 2),
                                    rect.width() + border_width,
                                    rect.height() + border_width)

        pen = QtGui.QPen(border_color, border_width)
        pen.setCosmetic(self.viewer().get_zoom() < 0.0)
        path = QtGui.QPainterPath()
        path.addRoundedRect(border_rect, radius, radius)
        painter.setBrush(QtCore.Qt.NoBrush)
        painter.setPen(pen)
        painter.drawPath(path)

        painter.restore()

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.MouseButton.LeftButton:
            start = PortItem().boundingRect().width()
            end = self.boundingRect().width() - start
            x_pos = event.pos().x()
            if not start <= x_pos <= end:
                event.ignore()
        super(NodeItem, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if event.modifiers() == QtCore.Qt.AltModifier:
            event.ignore()
            return
        super(NodeItem, self).mouseReleaseEvent(event)

    def itemChange(self, change, value):
        if change == self.ItemSelectedChange and self.scene():
            self.reset_pipes()
            if value:
                self.hightlight_pipes()
            self.setZValue(Z_VAL_NODE)
            if not self.selected:
                self.setZValue(Z_VAL_NODE + 1)

        return super(NodeItem, self).itemChange(change, value)

    def _tooltip_disable(self, state):
        tooltip = '<b>{}</b>'.format(self._properties['name'])
        if state:
            tooltip += ' <font color="red"><b>(DISABLED)</b></font>'
        tooltip += '<br/>{}<br/>'.format(self._properties['type'])
        self.setToolTip(tooltip)

    def _set_base_size(self):
        """
        setup initial base size.
        """
        self._width = NODE_WIDTH
        self._height = NODE_HEIGHT
        width, height = self.calc_size()
        if width > self._width:
            self._width = width
        if height > self._height:
            self._height = height

    def _set_text_color(self, color):
        """
        set text color.

        Args:
            color (tuple): color value in (r, g, b, a).
        """
        text_color = QtGui.QColor(*color)
        for port, text in self._input_items.items():
            text.setDefaultTextColor(text_color)
        for port, text in self._output_items.items():
            text.setDefaultTextColor(text_color)
        self._text_item.setDefaultTextColor(text_color)

    def activate_pipes(self):
        """
        active pipe color.
        """
        ports = self.inputs + self.outputs
        for port in ports:
            for pipe in port.connected_pipes:
                pipe.activate()

    def hightlight_pipes(self):
        """
        highlight pipe color.
        """
        ports = self.inputs + self.outputs
        for port in ports:
            for pipe in port.connected_pipes:
                pipe.highlight()

    def reset_pipes(self):
        """
        reset the pipe color.
        """
        ports = self.inputs + self.outputs
        for port in ports:
            for pipe in port.connected_pipes:
                pipe.reset()

    def calc_size(self):
        """
        calculate minimum node size.
        """
        width = 0.0
        if self._widgets:
            widget_widths = [
                w.boundingRect().width() for w in self._widgets.values()
            ]
            width = max(widget_widths)
        if self._text_item.boundingRect().width() > width:
            width = self._text_item.boundingRect().width()

        port_height = 0.0
        if self._input_items:
            input_widths = []
            for port, text in self._input_items.items():
                input_width = port.boundingRect().width() * 2
                if text.isVisible():
                    input_width += text.boundingRect().width()
                input_widths.append(input_width)
            width += max(input_widths)
            port = list(self._input_items.keys())[0]
            port_height = port.boundingRect().height() * 2
        if self._output_items:
            output_widths = []
            for port, text in self._output_items.items():
                output_width = port.boundingRect().width() * 2
                if text.isVisible():
                    output_width += text.boundingRect().width()
                output_widths.append(output_width)
            width += max(output_widths)
            port = list(self._output_items.keys())[0]
            port_height = port.boundingRect().height() * 2

        in_count = len([p for p in self.inputs if p.isVisible()])
        out_count = len([p for p in self.outputs if p.isVisible()])
        height = port_height * (max([in_count, out_count]) + 2)
        if self._widgets:
            wid_height = sum(
                [w.boundingRect().height() for w in self._widgets.values()])
            if wid_height > height:
                height = wid_height + (wid_height / len(self._widgets))

        height += 10

        return width, height

    def arrange_icon(self):
        """
        Arrange node icon to the default top left of the node.
        """
        self._icon_item.setPos(2.0, 2.0)

    def arrange_label(self):
        """
        Arrange node label to the default top center of the node.
        """
        text_rect = self._text_item.boundingRect()
        text_x = (self._width / 2) - (text_rect.width() / 2)
        self._text_item.setPos(text_x, 1.0)

    def arrange_widgets(self):
        """
        Arrange node widgets to the default center of the node.
        """
        if not self._widgets:
            return
        wid_heights = sum(
            [w.boundingRect().height() for w in self._widgets.values()])
        pos_y = self._height / 2
        pos_y -= wid_heights / 2
        for name, widget in self._widgets.items():
            rect = widget.boundingRect()
            pos_x = (self._width / 2) - (rect.width() / 2)
            widget.setPos(pos_x, pos_y)
            pos_y += rect.height()

    def arrange_ports(self, padding_x=0.0, padding_y=0.0):
        """
        Arrange input, output ports in the node layout.
    
        Args:
            padding_x (float): horizontal padding.
            padding_y: (float): vertical padding.
        """
        width = self._width - padding_x
        height = self._height - padding_y

        # adjust input position
        inputs = [p for p in self.inputs if p.isVisible()]
        if inputs:
            port_width = inputs[0].boundingRect().width()
            port_height = inputs[0].boundingRect().height()
            chunk = (height / len(inputs))
            port_x = (port_width / 2) * -1
            port_y = (chunk / 2) - (port_height / 2)
            for port in inputs:
                port.setPos(port_x + padding_x, port_y + (padding_y / 2))
                port_y += chunk
        # adjust input text position
        for port, text in self._input_items.items():
            if not port.isVisible():
                continue
            txt_height = text.boundingRect().height() - 8.0
            txt_x = port.x() + port.boundingRect().width()
            txt_y = port.y() - (txt_height / 2)
            text.setPos(txt_x + 3.0, txt_y)
        # adjust output position
        outputs = [p for p in self.outputs if p.isVisible()]
        if outputs:
            port_width = outputs[0].boundingRect().width()
            port_height = outputs[0].boundingRect().height()
            chunk = height / len(outputs)
            port_x = width - (port_width / 2)
            port_y = (chunk / 2) - (port_height / 2)
            for port in outputs:
                port.setPos(port_x, port_y + (padding_y / 2))
                port_y += chunk
        # adjust output text position
        for port, text in self._output_items.items():
            if not port.isVisible():
                continue
            txt_width = text.boundingRect().width()
            txt_height = text.boundingRect().height() - 8.0
            txt_x = width - txt_width - (port.boundingRect().width() / 2)
            txt_y = port.y() - (txt_height / 2)
            text.setPos(txt_x - 1.0, txt_y)

    def offset_icon(self, x=0.0, y=0.0):
        """
        offset the icon in the node layout.

        Args:
            x (float): horizontal x offset
            y (float): vertical y offset
        """
        if self._icon_item:
            icon_x = self._icon_item.pos().x() + x
            icon_y = self._icon_item.pos().y() + y
            self._icon_item.setPos(icon_x, icon_y)

    def offset_label(self, x=0.0, y=0.0):
        """
        offset the label in the node layout.

        Args:
            x (float): horizontal x offset
            y (float): vertical y offset
        """
        icon_x = self._text_item.pos().x() + x
        icon_y = self._text_item.pos().y() + y
        self._text_item.setPos(icon_x, icon_y)

    def offset_widgets(self, x=0.0, y=0.0):
        """
        offset the node widgets in the node layout.

        Args:
            x (float): horizontal x offset
            y (float): vertical y offset
        """
        for name, widget in self._widgets.items():
            pos_x = widget.pos().x()
            pos_y = widget.pos().y()
            widget.setPos(pos_x + x, pos_y + y)

    def offset_ports(self, x=0.0, y=0.0):
        """
        offset the ports in the node layout.

        Args:
            x (float): horizontal x offset
            y (float): vertical y offset
        """
        for port, text in self._input_items.items():
            port_x, port_y = port.pos().x(), port.pos().y()
            text_x, text_y = text.pos().x(), text.pos().y()
            port.setPos(port_x + x, port_y + y)
            text.setPos(text_x + x, text_y + y)
        for port, text in self._output_items.items():
            port_x, port_y = port.pos().x(), port.pos().y()
            text_x, text_y = text.pos().x(), text.pos().y()
            port.setPos(port_x + x, port_y + y)
            text.setPos(text_x + x, text_y + y)

    def post_init(self, viewer=None, pos=None):
        """
        Called after node has been added into the scene.
        Adjust the node layout and form after the node has been added.

        Args:
            viewer (NodeGraphQt.widgets.viewer.NodeViewer): not used
            pos (tuple): cursor position.
        """
        # setup initial base size.
        self._set_base_size()
        # set text color when node is initialized.
        self._set_text_color(self.text_color)
        # set the tooltip
        self._tooltip_disable(self.disabled)

        # --- setup node layout ---

        # arrange label text
        self.arrange_label()
        self.offset_label(0.0, 5.0)

        # arrange icon
        self.arrange_icon()
        self.offset_icon(5.0, 2.0)

        # arrange node widgets
        self.arrange_widgets()
        self.offset_widgets(0.0, 10.0)

        # arrange input and output ports.
        self.arrange_ports(padding_y=35.0)
        self.offset_ports(0.0, 15.0)

        # set initial node position.
        if pos:
            self.xy_pos = pos

    @property
    def icon(self):
        return self._properties['icon']

    @icon.setter
    def icon(self, path=None):
        self._properties['icon'] = path
        path = path or ICON_NODE_BASE
        pixmap = QtGui.QPixmap(path)
        if pixmap.size().height() > NODE_ICON_SIZE:
            pixmap = pixmap.scaledToHeight(NODE_ICON_SIZE,
                                           QtCore.Qt.SmoothTransformation)
        self._icon_item.setPixmap(pixmap)
        if self.scene():
            self.post_init()

    @AbstractNodeItem.width.setter
    def width(self, width=0.0):
        w, h = self.calc_size()
        width = width if width > w else w
        AbstractNodeItem.width.fset(self, width)

    @AbstractNodeItem.height.setter
    def height(self, height=0.0):
        w, h = self.calc_size()
        h = 70 if h < 70 else h
        height = height if height > h else h
        AbstractNodeItem.height.fset(self, height)

    @AbstractNodeItem.disabled.setter
    def disabled(self, state=False):
        AbstractNodeItem.disabled.fset(self, state)
        for n, w in self._widgets.items():
            w.widget.setDisabled(state)
        self._tooltip_disable(state)
        self._x_item.setVisible(state)

    @AbstractNodeItem.selected.setter
    def selected(self, selected=False):
        AbstractNodeItem.selected.fset(self, selected)
        if selected:
            self.hightlight_pipes()

    @AbstractNodeItem.name.setter
    def name(self, name=''):
        AbstractNodeItem.name.fset(self, name)
        self._text_item.setPlainText(name)
        if self.scene():
            self.post_init()

    @property
    def inputs(self):
        """
        Returns:
            list[PortItem]: input port graphic items.
        """
        return list(self._input_items.keys())

    @property
    def outputs(self):
        """
        Returns:
            list[PortItem]: output port graphic items.
        """
        return list(self._output_items.keys())

    def add_input(self, name='input', multi_port=False, display_name=True):
        """
        Args:
            name (str): name for the port.
            multi_port (bool): allow multiple connections.
            display_name (bool): display the port name. 

        Returns:
            PortItem: input item widget
        """
        port = PortItem(self)
        port.name = name
        port.port_type = IN_PORT
        port.multi_connection = multi_port
        port.display_name = display_name
        text = QGraphicsTextItem(port.name, self)
        text.font().setPointSize(8)
        text.setFont(text.font())
        text.setVisible(display_name)
        self._input_items[port] = text
        if self.scene():
            self.post_init()
        return port

    def add_output(self, name='output', multi_port=False, display_name=True):
        """
        Args:
            name (str): name for the port.
            multi_port (bool): allow multiple connections.
            display_name (bool): display the port name.

        Returns:
            PortItem: output item widget
        """
        port = PortItem(self)
        port.name = name
        port.port_type = OUT_PORT
        port.multi_connection = multi_port
        port.display_name = display_name
        text = QGraphicsTextItem(port.name, self)
        text.font().setPointSize(8)
        text.setFont(text.font())
        text.setVisible(display_name)
        self._output_items[port] = text
        if self.scene():
            self.post_init()
        return port

    def get_input_text_item(self, port_item):
        """
        Args:
            port_item (PortItem): port item.

        Returns:
            QGraphicsTextItem: graphic item used for the port text.
        """
        return self._input_items[port_item]

    def get_output_text_item(self, port_item):
        """
        Args:
            port_item (PortItem): port item.

        Returns:
            QGraphicsTextItem: graphic item used for the port text.
        """
        return self._output_items[port_item]

    @property
    def widgets(self):
        return dict(self._widgets)

    def add_combo_menu(self, name='', label='', items=None, tooltip=''):
        items = items or []
        widget = NodeComboBox(self, name, label, items)
        widget.setToolTip(tooltip)
        self.add_widget(widget)
        return widget

    def add_text_input(self, name='', label='', text='', tooltip=''):
        widget = NodeLineEdit(self, name, label, text)
        widget.setToolTip(tooltip)
        self.add_widget(widget)
        return widget

    def add_checkbox(self,
                     name='',
                     label='',
                     text='',
                     state=False,
                     tooltip=''):
        widget = NodeCheckBox(self, name, label, text, state)
        widget.setToolTip(tooltip)
        self.add_widget(widget)
        return widget

    def add_widget(self, widget):
        if isinstance(widget, NodeBaseWidget):
            self._widgets[widget.name] = widget
        else:
            raise TypeError('{} is not an instance of a node widget.')

    def get_widget(self, name):
        widget = self._widgets.get(name)
        if widget:
            return widget
        raise KeyError('node has no widget "{}"'.format(name))

    def delete(self):
        for port, text in self._input_items.items():
            port.delete()
        for port, text in self._output_items.items():
            port.delete()
        super(NodeItem, self).delete()

    def from_dict(self, node_dict):
        super(NodeItem, self).from_dict(node_dict)
        widgets = node_dict.pop('widgets', {})
        for name, value in widgets.items():
            if self._widgets.get(name):
                self._widgets[name].value = value
コード例 #3
0
ファイル: scene.py プロジェクト: alchemist1234/Qt_Tank
class MaskScene(QGraphicsScene):
    _stage_text = 'STAGE %s'

    def __init__(self, main_window, stage=1):
        super().__init__()
        self.main_window = main_window
        self.stage = stage
        self.upper_mask = QGraphicsRectItem(0, 0, content_width, 0)
        self.lower_mask = QGraphicsRectItem(0, content_height, content_width, 0)
        self.stage_text_item = QGraphicsTextItem()
        self.mask_height = 0
        self.animation_timer_1 = QTimer()
        self.animation_timer_2 = QTimer()
        self.animation_timer_3 = QTimer()
        self.selected = None
        self.init()

    def init(self):
        mask_brush = QBrush()
        mask_brush.setColor(Qt.gray)
        mask_brush.setStyle(Qt.SolidPattern)
        mask_pen = QPen()
        mask_pen.setColor(Qt.gray)
        self.upper_mask.setBrush(mask_brush)
        self.lower_mask.setBrush(mask_brush)
        self.upper_mask.setPen(mask_pen)
        self.lower_mask.setPen(mask_pen)
        self.addItem(self.upper_mask)
        self.addItem(self.lower_mask)

        font = QFont()
        font.setPointSize(20)
        font.setBold(True)
        self.stage_text_item.setPlainText(self._stage_text % self.stage)
        self.stage_text_item.setFont(font)
        self.stage_text_item.setDefaultTextColor(Qt.black)
        self.stage_text_item.setX(content_width / 2 - int(self.stage_text_item.boundingRect().width() / 2))
        self.stage_text_item.setY(content_height / 2 - int(self.stage_text_item.boundingRect().height() / 2))

        self.animation_timer_1.setInterval(interval)
        self.animation_timer_1.timeout.connect(self.animation_in)

        self.animation_timer_2.setSingleShot(True)
        self.animation_timer_2.timeout.connect(self.animation_hold)
        self.animation_timer_2.setInterval(800)

        self.animation_timer_3.setInterval(interval)
        self.animation_timer_3.timeout.connect(self.animation_out)

    def next_stage(self):
        self.stage += 1
        self.stage_text_item.setPlainText(self._stage_text % self.stage)

    def reset_stage(self):
        self.stage = 0
        self.stage_text_item.setPlainText(self._stage_text % self.stage)

    def animation_in(self):
        self.mask_height += 10
        finished = False
        if self.mask_height > content_height / 2:
            self.mask_height = content_height / 2
            finished = True
        self.upper_mask.setRect(0, 0, content_width, self.mask_height)
        self.lower_mask.setRect(0, content_height - self.mask_height, content_width, self.mask_height)
        if finished:
            self.addItem(self.stage_text_item)
            self.animation_timer_1.stop()
            self.animation_timer_2.start()

    def animation_out(self):
        self.mask_height -= 10
        finished = False
        if self.mask_height < 0:
            self.mask_height = 0
            finished = True
        self.upper_mask.setRect(0, 0, content_width, self.mask_height)
        self.lower_mask.setRect(0, content_height - self.mask_height, content_width, self.mask_height)
        if finished:
            self.animation_timer_3.stop()
            self.main_window.start_game(self.selected)

    def animation_hold(self):
        self.removeItem(self.stage_text_item)
        self.animation_timer_3.start()
        self.main_window.enter_game_scene()

    def start_animation(self, selected: int):
        self.animation_timer_1.start()
        self.selected = selected
コード例 #4
0
class ExecutionIcon(QGraphicsEllipseItem):
    """An icon to show information about the item's execution."""

    _CHECK = "\uf00c"
    _CROSS = "\uf00d"
    _CLOCK = "\uf017"

    def __init__(self, parent):
        """
        Args:
            parent (ProjectItemIcon): the parent item
        """
        super().__init__(parent)
        self._parent = parent
        self._execution_state = "not started"
        self._text_item = QGraphicsTextItem(self)
        font = QFont('Font Awesome 5 Free Solid')
        self._text_item.setFont(font)
        parent_rect = parent.rect()
        self.setRect(0, 0, 0.5 * parent_rect.width(),
                     0.5 * parent_rect.height())
        self.setPen(Qt.NoPen)
        # pylint: disable=undefined-variable
        self.normal_brush = qApp.palette().window()
        self.selected_brush = qApp.palette().highlight()
        self.setBrush(self.normal_brush)
        self.setAcceptHoverEvents(True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, enabled=False)
        self.hide()

    def item_name(self):
        return self._parent.name()

    def _repaint(self, text, color):
        self._text_item.prepareGeometryChange()
        self._text_item.setPos(0, 0)
        self._text_item.setPlainText(text)
        self._text_item.setDefaultTextColor(color)
        size = self._text_item.boundingRect().size()
        dim_max = max(size.width(), size.height())
        rect_w = self.rect().width()
        self._text_item.setScale(rect_w / dim_max)
        self._text_item.setPos(self.sceneBoundingRect().center() -
                               self._text_item.sceneBoundingRect().center())
        self.show()

    def mark_execution_wating(self):
        self._execution_state = "waiting for dependencies"
        self._repaint(self._CLOCK, QColor("orange"))

    def mark_execution_started(self):
        self._execution_state = "in progress"
        self._repaint(self._CHECK, QColor("orange"))

    def mark_execution_finished(self, success, skipped):
        if success:
            self._execution_state = "skipped" if skipped else "completed"
            colorname = "orange" if skipped else "green"
            self._repaint(self._CHECK, QColor(colorname))
        else:
            self._execution_state = "failed"
            self._repaint(self._CROSS, QColor("red"))

    def hoverEnterEvent(self, event):
        tip = f"<p><b>Execution {self._execution_state}</b>. Select this item to see Console and Log messages.</p>"
        QToolTip.showText(event.screenPos(), tip)

    def hoverLeaveEvent(self, event):
        QToolTip.hideText()
コード例 #5
0
class GraphicsPortPainter:
    """The GraphicsPortPainter class provides a set of functions and configurations for
        painting a GraphicsPort object.
    """
    class DrawingState(Enum):
        Normal = 0
        Target = 1

    class PortNamePosition(Enum):
        Left = 0
        Right = 1

    drawing_state = DrawingState.Normal
    target_port_type = None

    def __init__(self, graphics_port: "GraphicsPort",
                 port_name_position: "PortNamePosition"):
        self.__graphics_port = graphics_port
        self.__port_name = QGraphicsTextItem(parent=graphics_port)
        self.__port_name.setPlainText(graphics_port._port.name)
        self.__port_name.setDefaultTextColor("#FFFFFF")
        self.__port_name.setFlag(QGraphicsItem.ItemStacksBehindParent)

        self.port_name_position = port_name_position

        # Colors/Pens/Brushes

        self.__color = TypeColor.get_color_for(graphics_port._port.port_type)

        self.__outline_pen = QPen(self.__color.darker())
        self.__outline_pen.setWidthF(2)
        self.__background_brush = QBrush(self.__color)

        self.__dashed_outline_pen = QPen(self.__color)
        self.__dashed_outline_pen.setStyle(Qt.DashLine)
        self.__dashed_outline_pen.setWidth(2)

    @property
    def port_name_position(self) -> "PortNamePosition":
        return self.__port_name_position

    @port_name_position.setter
    def port_name_position(self, position: "PortNamePosition"):
        if position == self.PortNamePosition.Left:
            self.__port_name.setPos(
                -self.__port_name.boundingRect().width() - 3, 1)
        elif position == self.PortNamePosition.Right:
            self.__port_name.setPos(3, 1)

        self.__port_name_position = position

    @property
    def color(self):
        return self.__color

    def paint_area(self):
        return QRectF(
            -self.__graphics_port.radius,
            -self.__graphics_port.radius,
            2 * self.__graphics_port.radius,
            2 * self.__graphics_port.radius,
        )

    def paint(
        self,
        painter: "QPainter",
        option: "QStyleOptionGraphicsItem",
        widget: "QWidget" = None,
    ):
        if (GraphicsPortPainter.drawing_state
                == GraphicsPortPainter.DrawingState.Target
                and self.__graphics_port.port_type
                == GraphicsPortPainter.target_port_type):
            painter.setPen(self.__dashed_outline_pen)
            painter.setBrush(Qt.NoBrush)
            painter.drawEllipse(self.__graphics_port.boundingRect())

        painter.setPen(self.__outline_pen)
        painter.setBrush(self.__background_brush)
        painter.drawEllipse(self.paint_area())
コード例 #6
0
ファイル: monitor_item.py プロジェクト: ralsina/xrandroll
class MonitorItem(QGraphicsRectItem, QObject):
    z = 0

    def __init__(self, *a, **kw):
        data = kw.pop("data")
        self.name = kw.pop("name")
        self.window = kw.pop("window")
        super().__init__(0, 0, 0, 0)
        self.setAcceptedMouseButtons(Qt.LeftButton)
        self.label = QGraphicsTextItem("", self)
        self.bottom_edge = QGraphicsRectItem(0, 0, 0, 0, self)
        self.bottom_edge.setBrush(QBrush("red", Qt.SolidPattern))
        self.update_visuals(data)

    def update_visuals(self, monitor):
        self.setRect(0, 0, monitor.res_x, monitor.res_y)
        self.setPos(monitor.pos_x, monitor.pos_y)
        if monitor.orientation == "normal":
            self.bottom_edge.setRect(0, monitor.res_y - 50, monitor.res_x, 50)
        elif monitor.orientation == "left":
            self.bottom_edge.setRect(monitor.res_x - 50, 0, 50, monitor.res_y)
        elif monitor.orientation == "inverted":
            self.bottom_edge.setRect(0, 0, monitor.res_x, 50)
        elif monitor.orientation == "right":
            self.bottom_edge.setRect(0, 0, 50, monitor.res_y)
        if monitor.replica_of:
            label_text = f"{self.name} [{','.join(monitor.replica_of)}]"
        else:
            label_text = self.name
        self.label.setPlainText(label_text)
        label_scale = min(
            self.rect().width() / self.label.boundingRect().width(),
            self.rect().height() / self.label.boundingRect().height(),
        )
        self.label.setScale(label_scale)
        if monitor.enabled:
            if monitor.primary:
                color = QColor("#eee8d5")
                color.setAlpha(200)
                self.setBrush(QBrush(color, Qt.SolidPattern))
                self.setZValue(1000)
            else:
                color = QColor("#ffffff")
                color.setAlpha(200)
                self.setBrush(QBrush(color, Qt.SolidPattern))
                self.setZValue(self.z)
                self.z -= 1
            self.show()
        else:
            color = QColor("#f1f1f1")
            color.setAlpha(200)
            self.setBrush(QBrush(color, Qt.SolidPattern))
            self.setZValue(-1000)
            self.hide()

    def mousePressEvent(self, event):
        self.window.pos_label.show()
        self.setCursor(Qt.ClosedHandCursor)
        self.orig_pos = self.pos()
        self.window.ui.screenCombo.setCurrentText(self.name)

    def mouseReleaseEvent(self, event):
        self.setCursor(Qt.OpenHandCursor)
        self.window.pos_label.hide()
        self.window.monitor_moved()

    def mouseMoveEvent(self, event):
        snaps_x, snaps_y = self.window.possible_snaps(self.name)
        view = event.widget().parent()
        click_pos = event.buttonDownScreenPos(Qt.LeftButton)
        current_pos = event.screenPos()
        new_pos = view.mapFromScene(self.orig_pos) + current_pos - click_pos
        new_pos = view.mapToScene(new_pos)
        delta = view.mapToScene(0, 20).y()
        if not event.modifiers() & Qt.AltModifier:
            # Check for snaps
            x = new_pos.x()
            delta_x = min((abs(x - sx), i) for i, sx in enumerate(snaps_x))
            if delta_x[0] < delta:  # snap
                new_pos.setX(int(snaps_x[delta_x[1]]))
            y = new_pos.y()
            delta_y = min((abs(y - sy), i) for i, sy in enumerate(snaps_y))
            if delta_y[0] < delta:  # snap
                new_pos.setY(int(snaps_y[delta_y[1]]))
        self.setPos(new_pos)
        self.window.show_pos(int(self.pos().x()), int(self.pos().y()))
コード例 #7
0
class MonitorItem(QGraphicsRectItem, QObject):
    z = 0

    def __init__(self, *a, **kw):
        data = kw.pop("data")
        self.name = kw.pop("name")
        self.window = kw.pop("window")
        super().__init__(0, 0, 0, 0)
        self.setAcceptedMouseButtons(Qt.LeftButton)
        self.label = QGraphicsTextItem("", self)
        self.bottom_edge = QGraphicsRectItem(0, 0, 0, 0, self)
        self.bottom_edge.setBrush(QBrush("red", Qt.SolidPattern))
        self.update_visuals(data)

    def update_visuals(self, data):
        self.setRect(0, 0, data["res_x"], data["res_y"])
        self.setPos(data["pos_x"], data["pos_y"])
        if data["orientation"] == 0:
            self.bottom_edge.setRect(0, data["res_y"] - 50, data["res_x"], 50)
        elif data["orientation"] == 1:
            self.bottom_edge.setRect(data["res_x"] - 50, 0, 50, data["res_y"])
        elif data["orientation"] == 2:
            self.bottom_edge.setRect(0, 0, data["res_x"], 50)
        elif data["orientation"] == 3:
            self.bottom_edge.setRect(0, 0, 50, data["res_y"])
        if data["replica_of"]:
            label_text = f"{self.name} [{','.join(data['replica_of'])}]"
        else:
            label_text = self.name
        self.label.setPlainText(label_text)
        label_scale = min(
            self.rect().width() / self.label.boundingRect().width(),
            self.rect().height() / self.label.boundingRect().height(),
        )
        self.label.setScale(label_scale)
        if data["enabled"]:
            if data["primary"]:
                color = QColor("#eee8d5")
                color.setAlpha(200)
                self.setBrush(QBrush(color, Qt.SolidPattern))
                self.setZValue(1000)
            else:
                color = QColor("#ffffff")
                color.setAlpha(200)
                self.setBrush(QBrush(color, Qt.SolidPattern))
                self.setZValue(self.z)
                self.z -= 1
        else:
            color = QColor("#f1f1f1")
            color.setAlpha(200)
            self.setBrush(QBrush(color, Qt.SolidPattern))
            self.setZValue(-1000)

        if not data["current_mode"]:  # Disconnected or disabled
            self.hide()
        else:
            self.show()

    def mousePressEvent(self, event):
        self.window.pos_label.show()
        self.setCursor(Qt.ClosedHandCursor)
        self.orig_pos = self.pos()
        self.window.ui.screenCombo.setCurrentText(self.name)

    def mouseReleaseEvent(self, event):
        self.setCursor(Qt.OpenHandCursor)
        self.window.monitor_moved()
        self.window.pos_label.hide()

    def mouseMoveEvent(self, event):
        view = event.widget().parent()
        click_pos = event.buttonDownScreenPos(Qt.LeftButton)
        current_pos = event.screenPos()
        self.setPos(
            view.mapToScene(
                view.mapFromScene(self.orig_pos) + current_pos - click_pos))
        self.window.show_pos(int(self.pos().x()), int(self.pos().y()))
コード例 #8
0
class GraphicsNodePainter:
    def __init__(self, graphics_node: "GraphicsNode"):
        self.__graphics_node = graphics_node

        # Dimensions
        self.padding = 12
        self.clickable_margin = 15
        self.round_edge_size = 10
        self.window_outline_width = 4

        # Colors/Pens/Brushes
        self.__title_color = Qt.white
        self.__outline_selected_color = QColor("#FFA637")
        self.__outline_default_color = QColor("#000000")

        self.__outline_pen = QPen(self.__outline_default_color)
        self.__title_background_brush = QBrush(QColor("#FF313131"))
        self.__background_brush = QBrush(QColor("#E3212121"))

        self.__window_markers_pen = QPen(self.__outline_default_color)
        self.__window_markers_brush = QBrush(self.__outline_default_color)

        # Graphics Components
        self.__graphics_title = QGraphicsTextItem(parent=graphics_node)
        self.__graphics_title.setDefaultTextColor(self.__title_color)
        self.__graphics_title.setPlainText(self.__graphics_node.title)
        self.__graphics_title.setPos(self.padding, 0)

        # Position ProxyWidget
        self.repositionWidget()

        # position GraphicsPort objects
        def position_graphics_ports(x_offset, graphics_ports_dict):
            for i, graphics_port in enumerate(graphics_ports_dict.values()):
                graphics_port.setPos(
                    x_offset,
                    self.title_height() + (graphics_port.radius * 4) * (i + 1))

        position_graphics_ports(0, self.__graphics_node.inputs)
        position_graphics_ports(self.boundingRect().width(),
                                self.__graphics_node.outputs)

    @property
    def outline_selected_color(self) -> "QColor":
        return self.__outline_selected_color

    @outline_selected_color.setter
    def outline_selected_color(self, color: "QColor"):
        self.__outline_selected_color = color

    @property
    def outline_default_color(self) -> "QColor":
        return self.__outline_default_color

    @outline_default_color.setter
    def outline_default_color(self, color: "QColor"):
        self.__outline_default_color = color

    def boundingRect(self) -> "QRectF":
        return self.background_paint_area()

    def background_paint_area(self) -> "QRectF":
        proxy_rect = self.__graphics_node._proxy_widget.boundingRect()

        return proxy_rect.adjusted(
            0,
            0,
            self.padding * 2,
            self.title_height() + self.padding * 2,
        ).normalized()

    def repositionWidget(self):
        self.__graphics_node._proxy_widget.setPos(
            self.padding,
            self.title_height() + self.padding)

    def recalculateGeometry(self):
        for graphics_port in self.__graphics_node.outputs.values():
            graphics_port.setX(self.boundingRect().width())

    def itemChange(self, change: "QGraphicsItem.GraphicsItemChange",
                   value: Any) -> Any:
        if change == QGraphicsItem.ItemSelectedChange:
            self.__outline_pen.setColor(self.__outline_selected_color if value
                                        else self.__outline_default_color)

        return value

    def title_height(self) -> int:
        """Returns the height of the title graphics item."""
        return self.__graphics_title.boundingRect().height()

    def paint(self, painter: "QPainter", option: "QStyleOptionGraphicsItem",
              widget: "QWidget"):
        """Paints the GraphicsNode item."""

        self.__paint_background(painter)
        self.__paint_title_background(painter)
        self.__paint_outline(painter)
        self.__paint_window_markers(painter)

    def __paint_background(self, painter: "QPainter"):
        """Paints the background of the node. Plain color, no lines."""
        path_background = QPainterPath()
        path_background.addRoundedRect(
            self.background_paint_area(),
            self.round_edge_size,
            self.round_edge_size,
        )

        painter.setPen(Qt.NoPen)
        painter.setBrush(self.__background_brush)

        painter.drawPath(path_background.simplified())

    def __paint_title_background(self, painter: "QPainter"):
        """Paints a little background behind the title text, at the top of the node."""
        title_rect = self.__graphics_title.boundingRect()

        path_title_background = QPainterPath()
        path_title_background.setFillRule(Qt.WindingFill)
        path_title_background.addRoundedRect(
            0,
            0,
            self.background_paint_area().width(),
            title_rect.height(),
            self.round_edge_size,
            self.round_edge_size,
        )

        # (Drawing rects to hide the two botton round edges)
        path_title_background.addRect(
            0,
            title_rect.height() - self.round_edge_size,
            self.round_edge_size,
            self.round_edge_size,
        )

        path_title_background.addRect(
            self.background_paint_area().width() - self.round_edge_size,
            title_rect.height() - self.round_edge_size,
            self.round_edge_size,
            self.round_edge_size,
        )

        painter.setPen(Qt.NoPen)
        painter.setBrush(self.__title_background_brush)
        painter.drawPath(path_title_background.simplified())

    def __paint_window_markers(self, painter: "QPainter"):
        title_width = self.__graphics_title.boundingRect().width()

        for i, parent_window in reversed(
                list(enumerate(self.__graphics_node.parent_node_windows))):
            self.__window_markers_brush.setColor(
                parent_window.color_identifier)
            self.__window_markers_pen.setColor(
                parent_window.color_identifier.darker())

            painter.setPen(self.__window_markers_pen)
            painter.setBrush(self.__window_markers_brush)
            painter.drawRect(title_width + 20 + i * 25, 8, 15, 15)

    def __paint_outline(self, painter: "QPainter"):
        """Paints the outline of the node. Depending on if its selected or not, the
        color of the outline changes."""
        path_outline = QPainterPath()
        path_outline.addRoundedRect(
            self.boundingRect(),
            self.round_edge_size,
            self.round_edge_size,
        )

        painter.setPen(self.__outline_pen)
        painter.setBrush(Qt.NoBrush)
        painter.drawPath(path_outline.simplified())