Ejemplo n.º 1
0
    def update_data(self,
                    rect: QRectF,
                    angle: float,
                    keep_original: bool = True) -> None:
        """
        Method to update position and angle of this item

        :param rect: The new bounding rect of this item
        :param angle: The new angle of this item
        :param keep_original: If true, the position and angle before the change will be stored.
        Used for preview purposes
        :return: None
        """
        if not keep_original:
            self.rect = rect
            self.x = rect.x()
            self.y = rect.y()
            self.width = rect.width()
            self.height = rect.height()
            self.center = rect.center().x(), rect.center().y()
            self.angle = angle
            self.preview = False
            self.changed = True
        else:
            self.preview = True
        self.setRotation(0)
        self.setRect(rect)
        self.setTransformOriginPoint(rect.center())
        self.setRotation(angle)
        self.edit_rect.setRotation(0)
        self.edit_rect.setRect(rect)
        self.edit_rect.setTransformOriginPoint(rect.center())
        self.edit_rect.setRotation(angle)
Ejemplo n.º 2
0
def painter_rotate(painter: QPainter, rect: QRectF, angle: int = 0) -> QRectF:
    """Context manager rotating and restoring the painter

    :param painter: Painter, which is rotated
    :param rect: Rect to be painted in
    :param angle: Rotataion angle must be in (0, 90, 180, 270)

    """

    supported_angles = 0, 90, 180, 270
    angle = int(angle)

    if angle not in supported_angles:
        msg = "Rotation angle {} not in {}".format(angle, supported_angles)
        raise Warning(msg)
        return

    center_x, center_y = rect.center().x(), rect.center().y()

    with painter_save(painter):
        painter.translate(center_x, center_y)
        painter.rotate(angle)

        if angle in (0, 180):
            painter.translate(-center_x, -center_y)
        elif angle in (90, 270):
            painter.translate(-center_y, -center_x)
            rect = QRectF(rect.y(), rect.x(), rect.height(), rect.width())
        yield rect
Ejemplo n.º 3
0
 def drawValue(self, p: QPainter, baseRect: QRectF, value: float, delta: float):
     if value == self.m_min:
         return
     if self.m_barStyle == self.BarStyle.EXPAND:
         p.setBrush(self.palette().highlight())
         p.setPen(QPen(self.palette().shadow().color(), self.m_dataPenWidth))
         radius = (baseRect.height() / 2) / delta
         p.drawEllipse(baseRect.center(), radius, radius)
         return
     if self.m_barStyle == self.BarStyle.LINE:
         p.setPen(QPen(self.palette().highlight().color(), self.m_dataPenWidth))
         p.setBrush(Qt.NoBrush)
         if value == self.m_max:
             p.drawEllipse(baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2,
                                             -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2))
         else:
             arcLength = 360 / delta
             p.drawArc(baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2,
                                         -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2),
                       int(self.m_nullPosition * 16),
                       int(-arcLength * 16))
         return
     dataPath = QPainterPath()
     dataPath.setFillRule(Qt.WindingFill)
     if value == self.m_max:
         dataPath.addEllipse(baseRect)
     else:
         arcLength = 360 / delta
         dataPath.moveTo(baseRect.center())
         dataPath.arcTo(baseRect, self.m_nullPosition, -arcLength)
         dataPath.lineTo(baseRect.center())
     p.setBrush(self.palette().highlight())
     p.setPen(QPen(self.palette().shadow().color(), self.m_dataPenWidth))
     p.drawPath(dataPath)
Ejemplo n.º 4
0
class CartPoleShape:
    def __init__(self):
        self._boundingBox = QRectF(-239 / 2, -216 / 2, 239, 216)

        self._cartBody = QRectF(self._boundingBox.left(),
                                self._boundingBox.top() + 82,
                                self._boundingBox.width(), 106)

        self._cartJointBody = QRectF(
            self._cartBody.center().x() - 53 / 2,
            self._boundingBox.top() + 53 / 2, 53,
            self._cartBody.top() - self._boundingBox.top() - 53 / 2)

        self._cartJointBall = QRectF(
            self._cartJointBody.center().x() - self._cartJointBody.width() / 2,
            self._cartJointBody.top() - self._cartJointBody.width() / 2,
            self._cartJointBody.width(), self._cartJointBody.width())

        self._poleCenter = self._cartJointBall.center()

        self._leftGear = QRectF(self._boundingBox.left() + 43 - 26,
                                self._boundingBox.top() + 188 - 26, 26 * 2,
                                26 * 2)

        self._leftGearJoint = QRectF(self._boundingBox.left() + 43 - 2,
                                     self._boundingBox.top() + 188 - 2, 4, 4)

        self._rightGear = QRectF(self._boundingBox.left() + 194 - 26,
                                 self._boundingBox.top() + 188 - 26, 26 * 2,
                                 26 * 2)

        self._rightGearJoint = QRectF(self._boundingBox.left() + 194 - 2,
                                      self._boundingBox.top() + 188 - 2, 4, 4)

    def draw(self, qp, pen):
        qp.setPen(pen)
        qp.drawRect(self._cartBody)
        qp.drawLines([
            QLineF(self._cartJointBody.topLeft(),
                   self._cartJointBody.bottomLeft()),
            QLineF(self._cartJointBody.topRight(),
                   self._cartJointBody.bottomRight()),
            QLineF(self._cartJointBody.bottomLeft(),
                   self._cartJointBody.bottomRight())
        ])
        qp.drawArc(self._cartJointBall, 0, 180 * 16)
        qp.drawEllipse(self._leftGear)
        qp.drawEllipse(self._leftGearJoint)
        qp.drawEllipse(self._rightGear)
        qp.drawEllipse(self._rightGearJoint)

    # Computes the model matrix that moves the cart in center and has
    # size width
    def modelMatrix(self, center, width):
        return QTransform.fromScale(width / 239,
                                    width / 239) * QTransform.fromTranslate(
                                        -center.x(), -center.y())
Ejemplo n.º 5
0
	def __init__(self, parentItem, segments, colour):
		QGraphicsItem.__init__(self, parent=parentItem)
		self.colour_name = colour
		self.shape = QPainterPath()
		self.labels = QGraphicsItemGroup(self)
		self.bbox = QRectF(0, 0, 0, 0)
		for (p1, p2), label in segments:
			lvect = QVector2D(p2 - p1)
			lpath = QPainterPath()
			m = TWY_line_margin
			l = lvect.length()
			plst = [QPointF(-m, 0), QPointF(-m/3, -m), QPointF(l + m/3, -m), QPointF(l + m, 0), QPointF(l + m/3, m), QPointF(-m/3, m)]
			lpath.addPolygon(QPolygonF(plst))
			lrot = QTransform()
			lrot.rotateRadians(atan2(lvect.y(), lvect.x()))
			lpath = lrot.map(lpath)
			lpath.translate(p1)
			self.shape.addPath(lpath)
			rect = QRectF(p1, p2).normalized()
			if label != None:
				self.labels.addToGroup(TaxiwayLabelItem(label, rect.center(), self))
			self.bbox |= rect
		self.shape.setFillRule(Qt.WindingFill)
		self.mouse_highlight = False
		self.labels.setVisible(False)
Ejemplo n.º 6
0
    def paintEvent(self, e: QPaintEvent):

        contRect = self.contentsRect()
        handleRadius = round(0.24 * contRect.height())

        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)

        p.setPen(self._transparent_pen)
        barRect = QRectF(
            0, 0,
            contRect.width() - handleRadius, 0.40 * contRect.height()
        )
        barRect.moveCenter(contRect.center())
        rounding = barRect.height() / 2

        # the handle will move along this line
        trailLength = contRect.width() - 2 * handleRadius

        xPos = contRect.x() + handleRadius + trailLength * self._handle_position

        if self.pulse_anim.state() == QPropertyAnimation.Running:
            p.setBrush(
                self._pulse_checked_animation if
                self.isChecked() else self._pulse_unchecked_animation)
            p.drawEllipse(QPointF(xPos, barRect.center().y()),
                          self._pulse_radius, self._pulse_radius)

        if self.isChecked():
            p.setBrush(self._bar_checked_brush)
            p.drawRoundedRect(barRect, rounding, rounding)
            p.setBrush(self._handle_checked_brush)

        else:
            p.setBrush(self._bar_brush)
            p.drawRoundedRect(barRect, rounding, rounding)
            p.setPen(self._light_grey_pen)
            p.setBrush(self._handle_brush)

        p.drawEllipse(
            QPointF(xPos, barRect.center().y()),
            handleRadius, handleRadius)

        p.end()
Ejemplo n.º 7
0
    def resizeEvent(self, e):
        geo = QRectF(self.sceneRect())
        self.drawingOverlay.setRect(geo)
        self.noSelectionHighlight.setRect(geo)

        hr = self.helpOverlay.boundingRect()
        hr.moveCenter(geo.center())
        self.helpOverlay.setPos(hr.x(), hr.y())

        self._updateLayout()
Ejemplo n.º 8
0
    def getLinePoint(self, end):
        #rect = QRectF(self.pos(), QPoint(self.pos().x()+120, self.pos().y()+60))
        rect = QRectF(self.pos(), QSizeF(120, 60))
        #calculate center points
        left = QPointF(rect.topLeft().x(), rect.center().y())
        right = QPointF(rect.bottomRight().x(), rect.center().y())
        top = QPointF(rect.center().x(), rect.topLeft().y())
        bottom = QPointF(rect.center().x(), rect.bottomRight().y())

        if rect.topLeft().x() < end.x():
            #point is not left from rect
            if rect.bottomRight().x() < end.x():
                y1 = GeoHelper.getY(-1,
                                    rect.bottomRight().x(),
                                    rect.topLeft().y(), end.x())
                if end.y() < y1:
                    return "top", top
                y1 = GeoHelper.getY(1,
                                    rect.bottomRight().x(),
                                    rect.bottomRight().y(), end.x())
                if end.y() < y1:
                    return "right", right
                return "bottom", bottom
            elif rect.center().y() < end.y():
                return "bottom", bottom
            else:
                return "top", top
        else:
            #point is left from rect
            y1 = GeoHelper.getY(1,
                                rect.topLeft().x(),
                                rect.topLeft().y(), end.x())
            if end.y() < y1:
                return "top", top
            y1 = GeoHelper.getY(-1,
                                rect.topLeft().x(),
                                rect.bottomRight().y(), end.x())
            if end.y() < y1:
                return "left", left
            return "bottom", bottom
Ejemplo n.º 9
0
    def reset_view(self):
        # The SceneRect controls how far you can pan, make it larger than
        # just the bounding box so middle-click panning works
        panning_rect = QRectF(self.scene_bounding_rect)
        panning_rect_center = panning_rect.center()
        panning_rect_size = max(panning_rect.width(), panning_rect.height())*3
        panning_rect.setSize(QSizeF(panning_rect_size, panning_rect_size))
        panning_rect.moveCenter(panning_rect_center)
        self.setSceneRect(panning_rect)
        self.fitInView(self.scene_bounding_rect, Qt.KeepAspectRatio)
        self.zoom_view(0.8)

        self.update_grid()
Ejemplo n.º 10
0
    def _paint_stimulus_points_cell(self, painter, option, model_index):

        points = model_index.data(
            role=ProtocolSequence.Roles.STIMULUS_POINTS.value)

        if points:

            font_metrics = QFontMetrics(option.font)
            font_height = font_metrics.height()

            pixmap_plus1 = QPixmap()
            pixmap_plus1.load(Resources.get('one.png'))

            pixmap_random = QPixmap()
            pixmap_random.load(Resources.get('dice.png'))

            padding = 1

            max_img_height = max(pixmap_plus1.height(), pixmap_random.height())
            max_img_width = max(pixmap_plus1.width(), pixmap_random.width())

            cell_centre = (option.rect.x() + 0.5 * option.rect.width(),
                           option.rect.y() + 0.5 * option.rect.height())

            container_height = font_height + max_img_height + 2 * padding
            container_width = max_img_width + 2 * padding

            start_x = cell_centre[0] - container_width * (len(points) / 2)

            container = QRectF(start_x,
                               cell_centre[1] - 0.5 * container_height,
                               container_width, container_height)

            self.container_height = max(self.container_height,
                                        container.height())

            for point in points:
                pixmap = point.pattern.pixmap(max_img_height)
                painter.drawPixmap(container.topLeft().x() + padding,
                                   container.topLeft().y() + padding, pixmap)

                text = str(point.index())
                text_bounding_rect = font_metrics.boundingRect(text)
                painter.drawText(
                    container.center().x() - 0.5 * text_bounding_rect.width(),
                    container.bottomLeft().y() - padding, text)

                container.translate(container_width, 0)

            self.sizeHintChanged.emit(model_index)
Ejemplo n.º 11
0
    def _generate_bounding_rect(self):
        n1_p = Vector(*self.source_node.get_position())
        n2_p = Vector(*self.link.target.get_position())
        uv = (n2_p - n1_p).unit()

        start = n1_p + uv * self.source_node.get_radius()
        end = n2_p - uv * self.link.target.get_radius()

        #if multiple links ( always )
        if self.link.link_num % 2 == 0:
            targetDistance = self.link.link_num * 2
        else:
            targetDistance = (-self.link.link_num + 1) * 2

        start = start.rotated_new(self.arrow_separation * targetDistance, n1_p)
        end = end.rotated_new(-self.arrow_separation * targetDistance, n2_p)

        if self.link._failed:
            link_color = Qt.red
        else:
            link_color = Qt.green

        #rect calculation
        r = self.weight_rectangle_size

        mid = (start + end) / 2

        w_len = len(str(self.link.label)) * 4

        weight_v = Vector(r if w_len <= r else w_len, r)

        weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))

        if end.unit()[0] - start.unit()[0] > 0:
            link_paint = QLineF(QPointF(*start), QPointF(*end))
        else:
            link_paint = QLineF(QPointF(*end), QPointF(*start))

        center_of_rec_x = weight_rectangle.center().x()
        center_of_rec_y = weight_rectangle.center().y()

        rx = -(weight_v[0] * 0.5)
        ry = -(weight_v[1])

        #new_rec = QRectF(rx , ry, weight_v[0], 2 * weight_v[1])

        new_rec = QRectF(center_of_rec_x - 10, center_of_rec_y - 10, 15,
                         15).normalized()
        return new_rec
Ejemplo n.º 12
0
def grab_svg(scene):
    """
    Return a SVG rendering of the scene contents.

    Parameters
    ----------
    scene : :class:`CanvasScene`

    """
    from PyQt5.QtSvg import QSvgGenerator
    svg_buffer = QBuffer()
    gen = QSvgGenerator()
    gen.setOutputDevice(svg_buffer)

    items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10)

    if items_rect.isNull():
        items_rect = QRectF(0, 0, 10, 10)

    width, height = items_rect.width(), items_rect.height()
    rect_ratio = float(width) / height

    # Keep a fixed aspect ratio.
    aspect_ratio = 1.618
    if rect_ratio > aspect_ratio:
        height = int(height * rect_ratio / aspect_ratio)
    else:
        width = int(width * aspect_ratio / rect_ratio)

    target_rect = QRectF(0, 0, width, height)
    source_rect = QRectF(0, 0, width, height)
    source_rect.moveCenter(items_rect.center())

    gen.setSize(target_rect.size().toSize())
    gen.setViewBox(target_rect)

    painter = QPainter(gen)

    # Draw background.
    painter.setBrush(QBrush(Qt.white))
    painter.drawRect(target_rect)

    # Render the scene
    scene.render(painter, target_rect, source_rect)
    painter.end()

    buffer_str = bytes(svg_buffer.buffer())
    return buffer_str.decode("utf-8")
Ejemplo n.º 13
0
    def _debug_draw(self, painter, option, model_index):

        num_points = 9

        font_metrics = QFontMetrics(option.font)

        pixmap = QPixmap()
        pixmap.load(Resources.get('dice.png'))

        padding = 1

        max_img_height = pixmap.height()

        cell_centre = (option.rect.x() + 0.5 * option.rect.width(),
                       option.rect.y() + 0.5 * option.rect.height())

        font_height = font_metrics.height()

        container_height = font_height + max_img_height + 2 * padding
        container_width = pixmap.width() + 2 * padding

        start_x = cell_centre[0] - container_width * (num_points / 2)

        painter.drawLine(QPointF(cell_centre[0], 0),
                         QPointF(cell_centre[0], option.rect.height()))
        painter.drawLine(QPointF(0, cell_centre[1]),
                         QPointF(option.rect.width(), cell_centre[1]))

        container = QRectF(start_x, cell_centre[1] - 0.5 * container_height,
                           container_width, container_height)

        for i in range(0, num_points):
            painter.drawRect(container)

            painter.drawPixmap(container.topLeft().x() + padding,
                               container.topLeft().y() + padding, pixmap)

            text = str(i)
            text_bounding_rect = font_metrics.boundingRect(text)
            painter.drawText(
                container.center().x() - 0.5 * text_bounding_rect.width(),
                container.bottomLeft().y() - padding, text)

            container.translate(container_width, 0)
Ejemplo n.º 14
0
    def ScalePicture(self):
        if self.isStripModel:
            self.graphicsItem.setPos(0, 0)
        rect = QRectF(self.graphicsItem.pos(), QSizeF(
                self.pixMap.size()))
        flags = Qt.KeepAspectRatio
        unity = self.graphicsView.transform().mapRect(QRectF(0, 0, 1, 1))
        width = unity.width()
        height = unity.height()
        if width <= 0 or height <= 0:
            return
        self.graphicsView.scale(1 / width, 1 / height)
        viewRect = self.graphicsView.viewport().rect()
        sceneRect = self.graphicsView.transform().mapRect(rect)
        if sceneRect.width() <= 0 or sceneRect.height() <= 0:
            return
        x_ratio = viewRect.width() / sceneRect.width()
        y_ratio = viewRect.height() / sceneRect.height()
        if not self.isStripModel:
            x_ratio = y_ratio = min(x_ratio, y_ratio)
        else:
            x_ratio = y_ratio = max(x_ratio, y_ratio)
            # self.graphicsItem.setPos(p.x(), p.y()+height3)
            # self.graphicsView.move(p.x(), p.y()+height2)
            # self.graphicsView.move(p.x(), p.y()+height3)

        self.graphicsView.scale(x_ratio, y_ratio)
        if self.isStripModel:
            height2 = self.pixMap.size().height() / 2
            height3 = self.graphicsView.size().height()/2
            # height4 = self.graphicsView.geometry().height()/2
            # height5 = self.graphicsView.frameGeometry().height()/2
            height3 = height3/x_ratio
            # pos = height2
            p = self.graphicsItem.pos()
            # self.graphicsItem.setPos(0, 0)
            self.graphicsItem.setPos(p.x(), p.y()+height2-height3)

        self.graphicsView.centerOn(rect.center())
        for _ in range(abs(self.scaleCnt)):
            if self.scaleCnt > 0:
                self.graphicsView.scale(1.1, 1.1)
            else:
                self.graphicsView.scale(1/1.1, 1/1.1)
Ejemplo n.º 15
0
 def drawToolButtonContent(self, option, painter, widget):
     if option.state & QStyle.State_Enabled:
         pixmap = widget.pixmap(QIcon.Normal)
     else:
         pixmap = widget.pixmap(QIcon.Disabled)
     if not pixmap.isNull():
         margin = self._pixel_metrics[QStyle.PM_DefaultFrameWidth] + self._pixel_metrics[QStyle.PM_ButtonMargin]
         if option.features & QStyleOptionToolButton.MenuButtonPopup and option.direction == Qt.LeftToRight:
             right_offset = 1
         else:
             right_offset = 0
         content_rect = QRectF(
             self.proxy().subControlRect(QStyle.CC_ToolButton, option, QStyle.SC_ToolButton, widget)
         ).adjusted(margin, margin, -margin - right_offset, -margin)
         pixmap_rect = QRectF(pixmap.rect())
         pixmap_rect.moveCenter(content_rect.center())
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
         painter.drawPixmap(pixmap_rect.topLeft(), pixmap)
Ejemplo n.º 16
0
 def drawToolButtonContent(self, option, painter, widget):
     if option.state & QStyle.State_Enabled:
         pixmap = widget.pixmap(QIcon.Normal)
     else:
         pixmap = widget.pixmap(QIcon.Disabled)
     if not pixmap.isNull():
         margin = self._pixel_metrics[
             QStyle.PM_DefaultFrameWidth] + self._pixel_metrics[
                 QStyle.PM_ButtonMargin]
         if option.features & QStyleOptionToolButton.MenuButtonPopup and option.direction == Qt.LeftToRight:
             right_offset = 1
         else:
             right_offset = 0
         content_rect = QRectF(self.proxy().subControlRect(
             QStyle.CC_ToolButton, option, QStyle.SC_ToolButton,
             widget)).adjusted(margin, margin, -margin - right_offset,
                               -margin)
         pixmap_rect = QRectF(pixmap.rect())
         pixmap_rect.moveCenter(content_rect.center())
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
         painter.drawPixmap(pixmap_rect.topLeft(), pixmap)
Ejemplo n.º 17
0
    def setSelected(self, value):
        """
        Sets *value*-th glyph as the selected glyph, or none if *value* is
        None.

        *value* should be less than the number of glyphRecords present in the
        widget.
        """
        self._selected = value
        if self._selected is not None and self._glyphRecordsRects is not None:
            scrollArea = self._scrollArea
            if scrollArea is not None:
                rect = None
                for r, indexRecord in self._glyphRecordsRects.items():
                    if indexRecord == self._selected:
                        rect = QRectF(*r)
                        break
                if rect is not None:
                    center = rect.center()
                    scrollArea.ensureVisible(
                        center.x(), center.y(), .6 * rect.width(), .6 * rect.height())
        self.update()
Ejemplo n.º 18
0
    def paint(self, painter, option, widget=None):
        super(Link, self).paint(painter, option, widget)
        util = self.link.utilization()
        orangeColor = QColor(255, 165, 0)

        colour_values = {
            self.blue_threshold: QtCore.Qt.blue,
            self.green_threshold: QtCore.Qt.green,
            self.yellow_threshold: QtCore.Qt.yellow,
            self.orange_threshold: orangeColor,
        }

        colour_values_list = sorted(colour_values)
        link_color_index = bisect_left(colour_values_list, util)

        if self.link._failed:
            link_color = QtCore.Qt.red
        elif util == 0:
            link_color = QtCore.Qt.black
        elif util > int(orange_threshold):
            link_color = QtCore.Qt.magenta
        else:
            try:
                link_color_key = colour_values_list[link_color_index]
                link_color = colour_values[link_color_key]
                # print(util, link_color, link_color_index, link_color_key)
            except:
                # guard agains <100% thresholds value
                link_color = QtCore.Qt.magenta
        painter.save()
        painter.setFont(QFont(self.font_family, self.font_size / 3))

        if self.link.link_num % 2 == 0:
            targetDistance = self.link.link_num * 5
        else:
            targetDistance = (-self.link.link_num + 1) * 5
        # hours of calculation and still can't figure out where it's wrong
        n1_p = Vector(*self.source_node.get_position())
        n2_p = Vector(*self.link.target.get_position())
        x1_x0 = n2_p[0] - n1_p[0]
        y1_y0 = n2_p[1] - n1_p[1]

        if y1_y0 == 0:
            x2_x0 = 0
            y2_y0 = targetDistance
        else:
            angle = math.atan((x1_x0) / (y1_y0))
            x2_x0 = -targetDistance * math.cos(angle)
            y2_y0 = targetDistance * math.sin(angle)

        d0x = n1_p[0] + (1 * x2_x0)
        d0y = n1_p[1] + (1 * y2_y0)
        d1x = n2_p[0] + (1 * x2_x0)
        d1y = n2_p[1] + (1 * y2_y0)

        dx = (d1x - d0x,)
        dy = (d1y - d0y,)

        dr = math.sqrt(dx[0] * dx[0] + dy[0] * dy[0])

        endX = (d1x + d0x) / 2
        endY = (d1y + d0y) / 2

        len1 = dr - ((dr / 2) * math.sqrt(3))
        endX = endX + (len1 / dr)
        endY = endY + (len1 / dr)
        n1_p = Vector(d0x, d0y)
        n2_p = Vector(endX, endY)
        uv = (n2_p - n1_p).unit()
        d = distance(n1_p, n2_p)
        r = self.link.target.get_radius()
        arrow_head_pos = n2_p
        d = distance(n1_p, arrow_head_pos)
        uv_arrow = (arrow_head_pos - n1_p).unit()
        arrow_base_pos = n1_p + uv_arrow * (d - 2 * 2)
        nv_arrow = uv_arrow.rotated(math.pi / 2)

        painter.setRenderHints(
            QtGui.QPainter.Antialiasing
            | QtGui.QPainter.TextAntialiasing
            | QtGui.QPainter.SmoothPixmapTransform
            | QtGui.QPainter.HighQualityAntialiasing,
            True,
        )
        if self.link.highlight:
            painter.setPen(QPen(link_color, 3, 3))
        elif option.state & QtWidgets.QStyle.State_Selected:
            painter.setPen(QPen(link_color, 2, 4))
        else:
            painter.setPen(QPen(link_color, Qt.SolidLine))

        painter.setBrush(QBrush(link_color, Qt.SolidPattern))

        painter.drawPolygon(
            QPointF(*arrow_head_pos),
            QPointF(*(arrow_base_pos + nv_arrow * 2)),
            QPointF(*(arrow_base_pos - nv_arrow * 2)),
        )

        painter.drawLine(QPointF(d0x, d0y), QPointF(endX, endY))
        painter.setPen(QtGui.QPen(link_color, 1))
        # text
        if endX - d0x > 0:
            link_paint = QLineF(QPointF(d0x, d0y), QPointF(endX, endY))
        else:
            link_paint = QLineF(QPointF(endX, endY), QPointF(d0x, d0y))
        mid = (arrow_base_pos + n1_p) / 2
        if self.show_latency:
            w_len = (
                len(str(self.link.metric) + str(self.link.latency) + "------") / 3 * r
                + r / 3
            )
        else:
            w_len = len(str(self.link.metric)) / 3 * r + r / 3
        weight_v = Vector(w_len, 2)
        weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))
        painter.save()
        center_of_rec_x = weight_rectangle.center().x()
        center_of_rec_y = weight_rectangle.center().y()
        painter.translate(center_of_rec_x, center_of_rec_y)
        rx = -(weight_v[0] * 0.5)
        ry = -(weight_v[1])
        painter.rotate(-link_paint.angle())
        new_rec = QRect(rx, ry, weight_v[0], 2 * weight_v[1])

        if self.link._failed:
            painter.setBrush(QBrush(Qt.red, Qt.SolidPattern))

        elif option.state & QtWidgets.QStyle.State_Selected:
            pass

        painter.setBrush(QBrush(Qt.black, Qt.SolidPattern))

        painter.setPen(QtGui.QPen(Qt.black, Qt.SolidLine))
        painter.drawRect(QRect(rx, ry, weight_v[0], 2 * weight_v[1]))
        painter.setFont(QFont(self.font_family, self.font_size / 3.3))
        painter.setPen(QPen(Qt.white, Qt.SolidLine))
        if self.show_latency:
            painter.drawText(
                new_rec,
                Qt.AlignCenter,
                str(self.link.metric) + " -- " + str(self.link.latency) + "/ms",
            )
        else:
            painter.drawText(new_rec, Qt.AlignCenter, str(self.link.metric))

        painter.restore()

        painter.restore()
Ejemplo n.º 19
0
class TestPathFinding(TestCase):

################################################################################

    def setUp(self):
        """

        """

        #       --left     --right
        #       '          '
        #   I   |    II    |  III
        # ------+==========+------   --top
        #  VIII |  IX (in) |  IV
        # ------+==========+------   --bottom
        #  VII  |    VI    |   V

        self._offset = 10
        self._rect = QRectF(QPointF(-20, -10), QPointF(20, 10))
        self._pointI = QPointF(self._rect.left()-self._offset, self._rect.top()-self._offset)
        self._pointII = QPointF(self._rect.center().x(), self._rect.top()-self._offset)
        self._pointIII = QPointF(self._rect.right()+ self._offset, self._rect.top()- self._offset)
        self._pointIV = QPointF(self._rect.right()+self._offset, self._rect.center().y())
        self._pointV = QPointF(self._rect.right()+self._offset, self._rect.bottom()+self._offset)
        self._pointVI = QPointF(self._rect.center().x(), self._rect.bottom()+self._offset)
        self._pointVII = QPointF(self._rect.left()-self._offset, self._rect.bottom()+self._offset)
        self._pointVIII = QPointF(self._rect.left()-self._offset, self._rect.center().y())
        self._pointIX = self._rect.center()

        self._lineI_VII = QLineF(self._pointI, self._pointVII)
        self._lineI_V = QLineF(self._pointI, self._pointV)
        self._lineII = QLineF(self._pointII, QPointF(self._rect.center().x(), self._rect.top()))
        self._lineII_IV = QLineF(QPointF(self._rect.right()-self._offset, self._rect.top()-self._offset),
                                 QPointF(self._rect.right()+self._offset, self._rect.top()+self._offset))

################################################################################

    def testPointRectDist(self):
        """

        """

        lineI = PathFinding.pointRectDist(self._pointI, self._rect)
        self.assertEqual(lineI.p2(), self._rect.topLeft())
        self.assertEqual(lineI.length(), pow(pow(self._offset, 2)+pow(self._offset, 2), 0.5))
        lineII = PathFinding.pointRectDist(self._pointII, self._rect)
        self.assertEqual(lineII.p2(), QPointF(self._rect.center().x(), self._rect.top()))
        self.assertEqual(lineII.length(), self._offset)
        lineIII = PathFinding.pointRectDist(self._pointIII, self._rect)
        self.assertEqual(lineIII.p2(), self._rect.topRight())
        self.assertEqual(lineIII.length(), pow(pow(self._offset, 2)+pow(self._offset, 2), 0.5))
        lineIV = PathFinding.pointRectDist(self._pointIV, self._rect)
        self.assertEqual(lineIV.p2(), QPointF(self._rect.right(), self._rect.center().y()))
        self.assertEqual(lineIV.length(), self._offset)
        lineV = PathFinding.pointRectDist(self._pointV, self._rect)
        self.assertEqual(lineV.p2(), self._rect.bottomRight())
        self.assertEqual(lineV.length(), pow(pow(self._offset, 2)+pow(self._offset, 2), 0.5))
        lineVI = PathFinding.pointRectDist(self._pointVI, self._rect)
        self.assertEqual(lineVI.p2(), QPointF(self._rect.center().x(), self._rect.bottom()))
        self.assertEqual(lineVI.length(), self._offset)
        lineVII = PathFinding.pointRectDist(self._pointVII, self._rect)
        self.assertEqual(lineVII.p2(), self._rect.bottomLeft())
        self.assertEqual(lineVII.length(), pow(pow(self._offset, 2)+pow(self._offset, 2), 0.5))
        lineVIII = PathFinding.pointRectDist(self._pointVIII, self._rect)
        self.assertEqual(lineVIII.p2(), QPointF(self._rect.left(), self._rect.center().y()))
        self.assertEqual(lineVIII.length(), self._offset)
        lineIX = PathFinding.pointRectDist(self._pointIX, self._rect)
        self.assertEqual(lineIX.p2(), self._pointIX)
        self.assertEqual(lineIX.length(), 0)

################################################################################

    def testIntersects(self):
        """

        """

        rect = QRectF(QPointF(-50, -10), QPointF(50, 10))
        # line completely outside of the rectangle
        self.assertFalse(PathFinding.intersects(rect, QLineF(QPointF(-100, -50), QPointF(-100, 50))))
        # the line is a top side of the rectangle
        self.assertFalse(PathFinding.intersects(rect, QLineF(rect.topLeft(), rect.topRight())))
        # the line starts at the left corner of the rectangle and is not perpendicular to any of the rectangle sides;
        # the line ends outside of the rectangle, not going through it
        self.assertFalse(PathFinding.intersects(rect, QLineF(rect.topLeft(), QPointF(-100, -100))))
        # the line starts at the left corner of the rectangle and is perpendicular to the top side of the rectangle;
        # the line ends outside of the rectangle, not going through it
        self.assertFalse(PathFinding.intersects(rect, QLineF(rect.topLeft(), QPointF(rect.left(), rect.top() - 100))))
        # the line is horizontal and goes straight through the center of the rectangle
        self.assertTrue(PathFinding.intersects(rect, QLineF(QPointF(-100, 0), QPointF(100, 0))))
        # the line is vertical and goes straight through the center of the rectangle
        self.assertTrue(PathFinding.intersects(rect, QLineF(QPointF(0, -100), QPointF(0, 100))))
        # the line is vertical and goes up from the bottom right corner of the rectangle
        self.assertFalse(PathFinding.intersects(rect, QLineF(rect.bottomRight(), QPointF(rect.right(), rect.top()-100))))
        # the line is diagonal of the rectangle
        self.assertTrue(PathFinding.intersects(rect, QLineF(rect.topLeft(), rect.bottomRight())))
Ejemplo n.º 20
0
class Callout(QGraphicsItem):
    def __init__(self, chart):
        super().__init__(chart)

        self.m_chart = chart
        self.m_text = ""
        self.m_textRect = QRectF()
        self.m_rect = QRectF()
        self.m_anchor = QPointF()
        self.m_font = QFont()

    def boundingRect(self):
        anchor = self.mapFromParent(self.m_chart.mapToPosition(self.m_anchor))
        rect = QRectF()
        rect.setLeft(min(self.m_rect.left(), anchor.x()))
        rect.setRight(max(self.m_rect.right(), anchor.x()))
        rect.setTop(min(self.m_rect.top(), anchor.y()))
        rect.setBottom(max(self.m_rect.bottom(), anchor.y()))
        return rect

    def paint(self, painter, option, widget=None):
        path = QPainterPath()
        path.addRoundedRect(self.m_rect, 5, 5)

        anchor = self.mapFromParent(self.m_chart.mapToPosition(self.m_anchor))
        if not self.m_rect.contains(anchor):
            point1 = QPointF()
            point2 = QPointF()

            # establish the position of the anchor point in relation to m_rect
            above = anchor.y() <= self.m_rect.top()
            aboveCenter = (anchor.y() > self.m_rect.top()
                           and anchor.y() <= self.m_rect.center().y())
            belowCenter = (anchor.y() > self.m_rect.center().y()
                           and anchor.y() <= self.m_rect.bottom())
            below = anchor.y() > self.m_rect.bottom()

            onLeft = anchor.x() <= self.m_rect.left()
            leftOfCenter = (anchor.x() > self.m_rect.left()
                            and anchor.x() <= self.m_rect.center().x())
            rightOfCenter = (anchor.x() > self.m_rect.center().x()
                             and anchor.x() <= self.m_rect.right())
            onRight = anchor.x() > self.m_rect.right()

            # get the nearest m_rect corner.
            x = (onRight + rightOfCenter) * self.m_rect.width()
            y = (below + belowCenter) * self.m_rect.height()
            cornerCase = ((above and onLeft) or (above and onRight)
                          or (below and onLeft) or (below and onRight))
            vertical = abs(anchor.x() - x) > abs(anchor.y() - y)

            x1 = (x + leftOfCenter * 10 - rightOfCenter * 20 +
                  cornerCase * int(not vertical) *
                  (onLeft * 10 - onRight * 20))
            y1 = (y + aboveCenter * 10 - belowCenter * 20 +
                  cornerCase * int(vertical) * (above * 10 - below * 20))
            point1.setX(x1)
            point1.setY(y1)

            x2 = (x + leftOfCenter * 20 - rightOfCenter * 10 +
                  cornerCase * int(not vertical) *
                  (onLeft * 20 - onRight * 10))
            y2 = (y + aboveCenter * 20 - belowCenter * 10 +
                  cornerCase * int(vertical) * (above * 20 - below * 10))
            point2.setX(x2)
            point2.setY(y2)

            path.moveTo(point1)
            path.lineTo(anchor)
            path.lineTo(point2)
            path = path.simplified()

        painter.setBrush(QColor(255, 255, 255))
        painter.drawPath(path)
        painter.drawText(self.m_textRect, self.m_text)

    def mousePressEvent(self, event):
        event.setAccepted(True)

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            self.setPos(
                self.mapToParent(event.pos() -
                                 event.buttonDownPos(Qt.LeftButton)))
            event.setAccepted(True)
        else:
            event.setAccepted(False)

    def setText(self, text):
        self.m_text = text
        metrics = QFontMetrics(self.m_font)
        self.m_textRect = QRectF(
            metrics.boundingRect(QRect(0, 0, 150, 150), Qt.AlignLeft,
                                 self.m_text))
        self.m_textRect.translate(5, 5)
        self.prepareGeometryChange()
        self.m_rect = self.m_textRect.adjusted(-5, -5, 5, 5)

    def setAnchor(self, point):
        self.m_anchor = point

    def updateGeometry(self):
        self.prepareGeometryChange()
        self.setPos(
            self.m_chart.mapToPosition(self.m_anchor) + QPoint(10, -50))
Ejemplo n.º 21
0
# extra2.addEllipse(-0.35*IW, 0.5*IW, 0.7*IW, 0.3*IW)
# FWDPXI_PP += extra1
# FWDPXI_PP -= extra2

# REVPXI_PP.moveTo(-0.5*IW, -0.7*IW)
# REVPXI_PP.lineTo(0., 0.2*IW)
# REVPXI_PP.lineTo(0.5*IW, -0.7*IW)
# extra1 = QPainterPath()
# extra1.addEllipse(-0.5*IW, -0.9*IW, IW, 0.4*IW)
# REVPXI_PP += extra1

_RADIUS = styles.GRID_HELIX_RADIUS
_WEDGE_RECT_GAIN = 0.25
WEDGE_RECT = QRectF(0, 0, 2 * _RADIUS, 2 * _RADIUS)
WEDGE_RECT = WEDGE_RECT.adjusted(0, 0, _WEDGE_RECT_GAIN, _WEDGE_RECT_GAIN)
_WEDGE_RECT_CENTERPT = WEDGE_RECT.center()


class PropertyWrapperObject(QObject):
    """Summary

    Attributes:
        animations (dict): Description
        bondp2 (TYPE): Description
        item (TYPE): Description
        pen_alpha (TYPE): Description
        rotation (TYPE): Description
    """

    def __init__(self, item):
        """Summary
Ejemplo n.º 22
0
    def paint(self, painter):
        painter.setRenderHint(QPainter.Antialiasing)

        pixelRatio = self.devicePixelRatioF()
        rect = QRectF(0, 0,
                      self.width() * pixelRatio,
                      self.height() * pixelRatio)
        sz = QSizeF(self.width() * pixelRatio,
                    self.height() * pixelRatio).toSize()

        self.resizePixmap(sz)

        yOffset = rect.toRect().topLeft().y() + (100 - self.value() -
                                                 10) * sz.height() / 100

        # draw water
        waterImage = QImage(sz, QImage.Format_ARGB32_Premultiplied)
        waterPainter = QPainter()
        waterPainter.begin(waterImage)
        waterPainter.setRenderHint(QPainter.Antialiasing)
        waterPainter.setCompositionMode(QPainter.CompositionMode_Source)

        pointStart = QPointF(sz.width() / 2, 0)
        pointEnd = QPointF(sz.width() / 2, sz.height())
        linear = QLinearGradient(pointStart, pointEnd)
        startColor = QColor('#1F08FF')
        startColor.setAlphaF(1)
        endColor = QColor('#50FFF7')
        endColor.setAlphaF(0.28)
        linear.setColorAt(0, startColor)
        linear.setColorAt(1, endColor)
        linear.setSpread(QGradient.PadSpread)
        waterPainter.setPen(Qt.NoPen)
        waterPainter.setBrush(linear)
        waterPainter.drawEllipse(waterImage.rect().center(),
                                 sz.width() / 2 + 1,
                                 sz.height() / 2 + 1)

        waterPainter.setCompositionMode(QPainter.CompositionMode_SourceOver)
        waterPainter.drawImage(int(self.backXOffset), yOffset,
                               self.waterBackImage)
        waterPainter.drawImage(
            int(self.backXOffset) - self.waterBackImage.width(), yOffset,
            self.waterBackImage)
        waterPainter.drawImage(int(self.frontXOffset), yOffset,
                               self.waterFrontImage)
        waterPainter.drawImage(
            int(self.frontXOffset) - self.waterFrontImage.width(), yOffset,
            self.waterFrontImage)

        # draw pop
        if self.value() > 30:
            for pop in self.pops:
                popPath = QPainterPath()
                popPath.addEllipse(pop.xOffset * sz.width() / 100,
                                   (100 - pop.yOffset) * sz.height() / 100,
                                   pop.size * sz.width() / 100,
                                   pop.size * sz.height() / 100)
                waterPainter.fillPath(popPath, QColor(255, 255, 255,
                                                      255 * 0.3))

        if self.isTextVisible():
            font = waterPainter.font()
            rectValue = QRect()
            progressText = self.text().strip('%')

            if progressText == '100':
                font.setPixelSize(sz.height() * 35 / 100)
                waterPainter.setFont(font)

                rectValue.setWidth(sz.width() * 60 / 100)
                rectValue.setHeight(sz.height() * 35 / 100)
                rectValue.moveCenter(rect.center().toPoint())
                waterPainter.setPen(Qt.white)
                waterPainter.drawText(rectValue, Qt.AlignCenter, progressText)
            else:
                font.setPixelSize(sz.height() * 40 / 100)
                waterPainter.setFont(font)

                rectValue.setWidth(sz.width() * 45 / 100)
                rectValue.setHeight(sz.height() * 40 / 100)
                rectValue.moveCenter(rect.center().toPoint())
                rectValue.moveLeft(rect.left() + rect.width() * 0.45 * 0.5)

                waterPainter.setPen(Qt.white)
                waterPainter.drawText(rectValue, Qt.AlignCenter, progressText)
                font.setPixelSize(font.pixelSize() / 2)
                waterPainter.setFont(font)
                rectPerent = QRect(
                    QPoint(rectValue.right(),
                           rectValue.bottom() - rect.height() * 20 / 100),
                    QPoint(rectValue.right() + rect.width() * 20 / 100,
                           rectValue.bottom()))

                waterPainter.drawText(rectPerent, Qt.AlignCenter, '%')

        waterPainter.end()

        maskPixmap = QPixmap(sz)
        maskPixmap.fill(Qt.transparent)
        path = QPainterPath()
        path.addEllipse(QRectF(0, 0, sz.width(), sz.height()))
        maskPainter = QPainter()
        maskPainter.begin(maskPixmap)
        maskPainter.setRenderHint(QPainter.Antialiasing)
        maskPainter.setPen(QPen(Qt.white, 1))
        maskPainter.fillPath(path, QBrush(Qt.white))
        maskPainter.end()

        mode = QPainter.CompositionMode_SourceIn
        contentImage = QImage(sz, QImage.Format_ARGB32_Premultiplied)
        contentPainter = QPainter()
        contentPainter.begin(contentImage)
        contentPainter.setCompositionMode(QPainter.CompositionMode_Source)
        contentPainter.fillRect(contentImage.rect(), Qt.transparent)
        contentPainter.setCompositionMode(QPainter.CompositionMode_SourceOver)
        contentPainter.drawImage(0, 0, maskPixmap.toImage())
        contentPainter.setCompositionMode(mode)
        contentPainter.drawImage(0, 0, waterImage)
        contentPainter.setCompositionMode(
            QPainter.CompositionMode_DestinationOver)
        contentPainter.end()

        contentImage.setDevicePixelRatio(pixelRatio)
        painter.drawImage(self.rect(), contentImage)
Ejemplo n.º 23
0
    def paintEvent(self,event):
        global monster_data
        global dmg
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawPixmap(event.rect(),self.pixmap)

        if self.card is not None and self.card.ID is not 0:
            card = self.card
            # Draw card level at the bottom centered
            pen = QPen()
            if np.floor(card.lv) == monster_data[card.ID]['max_level']:
                lvstr = 'Lv.Max'
                brush = QBrush(QColor(252,232,131))
            else:
                lvstr = 'Lv.%d' % np.floor(card.lv)
                brush = QBrush(Qt.white)

            path = QPainterPath()
            pen.setWidth(0);
            pen.setBrush(Qt.black)

            font = QFont()
            font.setPointSize(11)
            font.setWeight(QFont.Black)
            
            path.addText(event.rect().x(),event.rect().y()+48,font,lvstr)

            rect = path.boundingRect()
            target = (event.rect().x()+event.rect().width())/2

            # center the rect in event.rect()
            path.translate(target-rect.center().x(), 0)

            painter.setPen(pen)
            painter.setBrush(QBrush(Qt.black))
            painter.drawPath(path.translated(.5,.5))

            painter.setPen(pen)
            painter.setBrush(brush)

            painter.drawPath(path)

            # Draw +eggs at the top right
            eggs = card.plus_atk+card.plus_hp+card.plus_rcv
            if eggs > 0:
                eggstr = '+%d' % eggs
                pen.setBrush(Qt.yellow)
                brush = QBrush(Qt.yellow)

                path = QPainterPath()
                pen.setWidth(0)
                pen.setBrush(Qt.black)
                font = QFont()
                font.setPointSize(11)
                font.setWeight(QFont.Black)
                path.addText(event.rect().x(),event.rect().y()+12,font,eggstr)

                path.translate(50-path.boundingRect().right()-3,0)
                #painter.setFont(font)
                painter.setPen(pen)
                painter.setBrush(QBrush(Qt.black))
                painter.drawPath(path.translated(.5,.5))

                painter.setPen(pen)
                painter.setBrush(brush)
                painter.drawPath(path)
                #painter.drawText(event.rect().adjusted(0,0,0,0),Qt.AlignRight, eggstr)

            # Draw awakenings at the top left in a green circle
            if card.current_awakening > 0:
                path = QPainterPath()
                rect = QRectF(event.rect()).adjusted(4,4,-36,-36)
                path.addEllipse(rect)
                painter.setBrush(QBrush(QColor(34,139,34)))
                pen.setBrush(Qt.white)
                pen.setWidth(1)
                painter.setPen(pen)
                painter.drawPath(path)

                path = QPainterPath()
                font.setPointSize(9)
                awkstr = ('%d' % card.current_awakening if
                        card.current_awakening < card.max_awakening else
                        '★')
                path.addText(rect.x(),rect.bottom(),font,awkstr)
                
                br = path.boundingRect()
                path.translate(rect.center().x()-br.center().x(),
                        rect.center().y()-br.center().y())

                pen.setBrush(QColor(0,0,0,0))
                pen.setWidth(0)
                painter.setPen(pen)
                painter.setBrush(QBrush(Qt.yellow))
                painter.drawPath(path)

            # Draw main attack damage
            #print(self.main_attack)
            if self.main_attack > 0:
                matkstr = '%d' % self.main_attack
                painter.setBrush(QBrush(COLORS[self.card.element[0]]))
                path = QPainterPath()
                font = QFont()
                font.setFamily('Helvetica')
                font.setWeight(QFont.Black)
                #font.setStretch(25)
                font.setPointSize(13)
                path.addText(rect.x(),rect.bottom(),font,matkstr)

                rect = QRectF(event.rect())
                br = path.boundingRect()
                path.translate(rect.center().x()-br.center().x(),
                        rect.center().y()-br.bottom()-1)

                # 
                pen.setBrush(Qt.black)
                pen.setWidthF(.75)
                painter.setPen(pen)
                painter.drawPath(path)

            # Draw sub attack damage
            #print(self.main_attack)
            if self.sub_attack > 0:
                satkstr = '%d' % self.sub_attack
                painter.setBrush(QBrush(COLORS[self.card.element[1]]))
                path = QPainterPath()
                font = QFont()
                font.setFamily('Helvetica')
                font.setWeight(QFont.Black)
                #font.setStretch(25)
                font.setPointSize(12)
                path.addText(rect.x(),rect.bottom(),font,satkstr)

                rect = QRectF(event.rect())
                br = path.boundingRect()
                path.translate(rect.center().x()-br.center().x(),
                        rect.center().y()-br.top()+1)

                # 
                pen.setBrush(Qt.black)
                pen.setWidthF(.75)
                painter.setPen(pen)
                painter.drawPath(path)
Ejemplo n.º 24
0
# extra2.addEllipse(-0.35*IW, 0.5*IW, 0.7*IW, 0.3*IW)
# FWDPXI_PP += extra1
# FWDPXI_PP -= extra2

# REVPXI_PP.moveTo(-0.5*IW, -0.7*IW)
# REVPXI_PP.lineTo(0., 0.2*IW)
# REVPXI_PP.lineTo(0.5*IW, -0.7*IW)
# extra1 = QPainterPath()
# extra1.addEllipse(-0.5*IW, -0.9*IW, IW, 0.4*IW)
# REVPXI_PP += extra1

_RADIUS = styles.SLICE_HELIX_RADIUS
_WEDGE_RECT_GAIN = 0.25
WEDGE_RECT = QRectF(0, 0, 2 * _RADIUS, 2 * _RADIUS)
WEDGE_RECT = WEDGE_RECT.adjusted(0, 0, _WEDGE_RECT_GAIN, _WEDGE_RECT_GAIN)
_WEDGE_RECT_CENTERPT = WEDGE_RECT.center()


class PropertyWrapperObject(QObject):
    def __init__(self, item):
        """Summary

        Args:
            item (TYPE): Description
        """
        super(PropertyWrapperObject, self).__init__()
        self.item = item
        self.animations = {}

    def __get_bondP2(self):
        """Summary
Ejemplo n.º 25
0
    def paint(self, painter, option, widget=None):
        super(L1CircuitItem, self).paint(painter, option, widget)

        painter.save()

        n1_p = Vector(*self.source_node.get_position())
        n2_p = Vector(*self.link.target.get_position())
        uv = (n2_p - n1_p).unit()

        start = n1_p + uv * self.source_node.get_radius()
        end = n2_p - uv * self.link.target.get_radius()

        #if multiple links ( always )
        if self.link.link_num % 2 == 0:
            targetDistance = self.link.link_num * 2
        else:
            targetDistance = (-self.link.link_num + 1) * 2

        start = start.rotated_new(self.arrow_separation * targetDistance, n1_p)
        end = end.rotated_new(-self.arrow_separation * targetDistance, n2_p)

        if self.link._failed:
            link_color = Qt.red
        else:
            link_color = Qt.green

        painter.setPen(QPen(link_color, Qt.SolidLine))
        painter.drawLine(QPointF(*start), QPointF(*end))

        painter.setPen(QPen(Qt.black, Qt.SolidLine))
        painter.setBrush(QBrush(
            Qt.black,
            Qt.SolidPattern,
        ))
        #rect calculation
        r = self.weight_rectangle_size

        mid = (start + end) / 2

        w_len = len(str(self.link.label)) * 4

        weight_v = Vector(r if w_len <= r else w_len, r)

        weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))

        if end.unit()[0] - start.unit()[0] > 0:
            link_paint = QLineF(QPointF(*start), QPointF(*end))
        else:
            link_paint = QLineF(QPointF(*end), QPointF(*start))

        center_of_rec_x = weight_rectangle.center().x()
        center_of_rec_y = weight_rectangle.center().y()

        painter.translate(center_of_rec_x, center_of_rec_y)

        rx = -(weight_v[0] * 0.5)
        ry = -(weight_v[1])

        painter.rotate(-link_paint.angle())
        new_rec = QRect(rx, ry, weight_v[0], 2 * weight_v[1])
        painter.drawRect(QRect(rx, ry, weight_v[0], 2 * weight_v[1]))
        painter.setFont(QFont(self.font_family, self.font_size / 4))

        painter.setPen(QPen(Qt.white, Qt.SolidLine))

        painter.drawText(new_rec, Qt.AlignCenter, str(self.link.label))

        painter.restore()
        painter.setPen(QPen(Qt.black, Qt.SolidLine))
        painter.setFont(QFont(self.font_family, self.font_size / 3))
Ejemplo n.º 26
0
class QtSocket(QGraphicsItem):
    def __init__(self,
                 socket_row,
                 mode,
                 shape,
                 hover_text="",
                 parent_item=None):
        # If creating a temporary connection, we create a fake socket, whose parent != socket row
        if parent_item is None:
            parent_item = socket_row

        super(QtSocket, self).__init__(parent_item)
        self._parentSocketRow = weakref.ref(socket_row)

        assert mode in ("input", "output"), mode
        self._mode = mode

        assert shape in (SocketTypes.circle, SocketTypes.square), shape
        self._shape = shape

        self._rect = QRectF(0, 0, 12, 12)
        self._color = QColor(200, 200, 200)
        self._brush = QBrush(self.color())
        self._pen = QPen(Qt.NoPen)

        self._hoverText = hover_text

        self._mixedColor = False

        self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, True)

        self._pen.setWidthF(1.0)

        self.setAcceptHoverEvents(True)
        self.setToolTip(hover_text)

        self._draggingConnection = None
        self._connections = []

    def mode(self):
        return self._mode

    def isInput(self):
        return self._mode == "input"

    def isOutput(self):
        return self._mode == "output"

    def parentNode(self):
        return self._parentSocketRow().parentNode()

    def parentSocketRow(self):
        return self._parentSocketRow()

    def borderEnabled(self):
        return self._pen.getStyle() == Qt.SolidLine

    def setBorderEnabled(self, value):
        if value:
            self._pen.setStyle(Qt.SolidLine)

        else:
            self._pen.setStyle(Qt.NoPen)

    def addConnection(self, connection):
        self._connections.append(connection)

    def removeConnection(self, connection):
        self._connections.remove(connection)

    def findConnection(self, socket):
        for connection in self._connections:
            if connection.endSocket() is socket:
                return connection

            if connection.startSocket() is socket:
                return connection

    def reorderConnection(self, connection, index):
        current_index = self._connections.index(connection)
        del self._connections[current_index]
        self._connections.insert(index, connection)

        # Update all paths
        for _connection in self._connections:
            _connection.updatePath()
            print("UPDATE PATHS")

    def getIndexInfo(self, connection):
        index = self._connections.index(connection)
        return index, len(self._connections)

    def hoverEnterEvent(self, event):
        self.parentNode().view().onSocketHoverEnter(self, event)

        for connection in self._connections:
            connection.onSocketHoverEnter()

    def hoverLeaveEvent(self, event):
        for connection in self._connections:
            connection.onSocketHoverExit()

        self.parentNode().view().onSocketHoverExit(self)

    def setMixedColor(self, value=True):
        self._mixedColor = value

    def setShape(self, shape):
        self._shape = shape

    def setColor(self, color):
        self._color.setRgb(color.red(), color.green(), color.blue())
        self._brush.setColor(self._color)
        self._pen.setColor(self._color.darker(150))

    def color(self):
        return QColor(self._color)

    def setColorRef(self, color):
        self._color = color

    def colorRef(self):
        return self._color

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton and event.modifiers(
        ) == Qt.NoModifier:
            from .connection import Connection

            if self.isOutput():
                connection = self._draggingConnection = Connection(self)
                self.scene().addItem(connection)
                connection.setActive(False)
                connection.show()

        elif event.button() == Qt.MiddleButton or \
                (event.button() == Qt.LeftButton and event.modifiers() == Qt.ControlModifier):

            self.parentNode().view().guiOnSocketInteract(self)

    def mouseMoveEvent(self, event):
        connection = self._draggingConnection

        if self.isOutput() and connection is not None:
            mouse_pos = connection.mapFromScene(event.scenePos())

            end_socket = connection.endSocket()
            end_socket.setPos(mouse_pos)

            connection.setActiveState(False)
            connection.updateEndPos()

        # QGraphicsItem.mouseMoveEvent(self, event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton and event.modifiers(
        ) == Qt.NoModifier:
            if self.isOutput():
                connection = self._draggingConnection

                start_socket = connection.startSocket()
                target_socket = connection.findClosestSocket()

                connection.onDeleted()
                self.scene().removeItem(connection)

                self._draggingConnection = None

                if target_socket is not None:
                    node = self.parentNode()

                    try:
                        node.view().guiCreateConnection(
                            start_socket, target_socket)

                    except NodeConnectionError:
                        pass

        # QGraphicsItem.mouseReleaseEvent(self, event)

    def setVisible(self, flag):
        QGraphicsItem.setVisible(self, flag)

        for connection in self._connections:
            connection.updateVisibility()

    def updateConnectionPositions(self):
        """Update connection positions when nodes are moved"""
        for connection in self._connections:
            if connection.startSocket() is self:
                connection.updateStartPos()

            else:
                connection.updateEndPos()

    def boundingRect(self):
        return self._rect

    def paint(self, painter, option, widget):

        painter.setBrush(self._brush)
        painter.setPen(self._pen)

        if self._shape == SocketTypes.circle:
            painter.drawEllipse(self._rect)

        elif self._shape == SocketTypes.square:
            painter.save()
            c = self._rect.center()
            painter.translate(c)
            painter.rotate(45)
            painter.scale(0.8, 0.8)
            painter.drawRect(self._rect.translated(-c))
            painter.restore()

        else:
            raise ValueError(self._shape)

        if self._mixedColor:
            painter.setBrush(painter.brush().color().darker(130))
            painter.drawChord(self._rect, 1 * 16, 180 * 16)

    def onDeleted(self):
        pass
Ejemplo n.º 27
0
 def multiplyDiameter(self, factor):
     r1 = self.rect()
     r2 = QRectF(0, 0, r1.width() * factor, r1.height() * factor)
     self.setRect(r2)
     self.setPos(self.pos() + r1.center() - r2.center())
Ejemplo n.º 28
0
 def multiplyDiameter(self, factor):
     r1 = self.rect()
     r2 = QRectF(0, 0, r1.width() * factor, r1.height() * factor)
     self.setRect(r2)
     self.setPos(self.pos() + r1.center() - r2.center())
Ejemplo n.º 29
0
    def _generate_bounding_rect(self):
        if self.link.link_num % 2 == 0:
            targetDistance = self.link.link_num * 5
        else:
            targetDistance = (-self.link.link_num + 1) * 5
        # hours of calculation and still can't figure out where it's wrong
        n1_p = Vector(*self.source_node.get_position())
        n2_p = Vector(*self.link.target.get_position())
        x1_x0 = n2_p[0] - n1_p[0]
        y1_y0 = n2_p[1] - n1_p[1]

        if y1_y0 == 0:
            x2_x0 = 0
            y2_y0 = targetDistance
        else:

            angle = math.atan((x1_x0) / (y1_y0))
            x2_x0 = -targetDistance * math.cos(angle)
            y2_y0 = targetDistance * math.sin(angle)

        d0x = n1_p[0] + (1 * x2_x0)
        d0y = n1_p[1] + (1 * y2_y0)
        d1x = n2_p[0] + (1 * x2_x0)
        d1y = n2_p[1] + (1 * y2_y0)

        dx = (d1x - d0x,)
        dy = (d1y - d0y,)

        dr = math.sqrt(dx[0] * dx[0] + dy[0] * dy[0])

        endX = (d1x + d0x) / 2
        endY = (d1y + d0y) / 2

        len1 = dr - ((dr / 2) * math.sqrt(3))
        endX = endX + (len1 / dr)
        endY = endY + (len1 / dr)

        n1_p = Vector(d0x, d0y)
        n2_p = Vector(endX, endY)

        uv = (n2_p - n1_p).unit()
        d = distance(n1_p, n2_p)
        r = self.link.target.get_radius()
        arrow_head_pos = n2_p
        d = distance(n1_p, arrow_head_pos)
        uv_arrow = (arrow_head_pos - n1_p).unit()
        arrow_base_pos = n1_p + uv_arrow * (d - 2 * 2)
        nv_arrow = uv_arrow.rotated(math.pi / 2)
        # text
        if endX - d0x > 0:
            link_paint = QLineF(QPointF(d0x, d0y), QPointF(endX, endY))
        else:
            link_paint = QLineF(QPointF(endX, endY), QPointF(d0x, d0y))

        mid = (arrow_base_pos + n1_p) / 2
        w_len = len(str(self.link.metric)) / 3 * r + r / 3
        weight_v = Vector(w_len, 2)
        weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))
        center_of_rec_x = weight_rectangle.center().x()
        center_of_rec_y = weight_rectangle.center().y()

        new_rec = QRectF(
            center_of_rec_x - 10, center_of_rec_y - 10, 20, 20
        ).normalized()
        return new_rec
Ejemplo n.º 30
0
    def drawPic(self, painter):
        painter.save()

        nItemY = 0
        #nWidth = self.width()
        nWidth = 755
        nWidth = nWidth if nWidth % 2 == 0 else nWidth + 1

        topLeft = QPointF(0, nItemY + 30)
        bottomRight = QPointF(nWidth, nItemY + ITEM_HEIGHT + ITEM_SPACE)
        ItemRect = QRectF(topLeft, bottomRight)

        painter.save()
        t = QTransform()
        t.translate(ItemRect.center().x(), ItemRect.center().y())
        painter.setTransform(t)

        rectTopLeft = QPointF()
        rectBottomRight = QPointF()
        textRect = QRectF(rectTopLeft, rectBottomRight)

        font = QFont('幼圆', 10)
        painter.setFont(font)

        path = QPainterPath()

        image = QImage()
        image.loadFromData(self.pic)
        pixmap = QPixmap.fromImage(image)

        pixelsWide = image.width()
        pixelsHigh = image.height()

        #m_wf = nWidth * 2 // 3
        ##pixelsHigh = ITEM_HEIGHT if pixelsWide < (m_wf*8//9) else (((pixelsWide // (nWidth // 2)) + 2) * ITEM_HEIGHT*2//5)
        #pixelsWide = pixelsWide if pixelsWide < (m_wf*8//9) else (m_wf*8//9)
        if pixelsWide > 540:
            pixelsWide = 540
            pixelsHigh = int(pixelsHigh * (540 / pixelsWide))

        if Orientation.Right == self.m_oritation:
            painter.save()
            painter.setPen(Qt.NoPen)
            painter.setBrush(HeaderBgColor)
            #绘制边框 头像边框
            painter.drawRoundedRect(nWidth // 2 - 55, -ITEM_HEIGHT // 2,
                                    HEAD_W_H, HEAD_W_H, 2, 2)
            painter.setPen(HeaderTextColor)
            #painter->drawPixmap(nWidth / 2 - 54, -ITEM_HEIGHT / 2 + 1, 48, 48, QPixmap(""));
            #绘制头像
            image = QImage()
            image.loadFromData(self.self_head)
            painter.drawPixmap(nWidth // 2 - 54, -ITEM_HEIGHT // 2 + 1,
                               HEAD_W_H, HEAD_W_H, QPixmap.fromImage(image))
            painter.restore()

            nX = (nWidth // 2) - 85 - pixelsWide
            if nX < 0:
                nX = -pixelsWide - 85 + nWidth // 2
            painter.save()

            textRect = QRectF(nX, -ITEM_HEIGHT // 2, pixelsWide + 20,
                              pixelsHigh)
            path.addRoundedRect(textRect, 3, 3)
            path.moveTo(nWidth // 2 - 65, -ITEM_HEIGHT // 2 + 12)
            path.lineTo(nWidth // 2 - 55, -ITEM_HEIGHT // 2 + 18)
            path.lineTo(nWidth // 2 - 65, -ITEM_HEIGHT // 2 + 21)
            painter.setPen(QColor(140, 170, 202))
            painter.drawPath(path)

            #painter.drawPixmap(nX + 10, -ITEM_HEIGHT / 2,pixelsWide, QPixmap(''))
            painter.restore()
            painter.setPen(Qt.white)
            textRect = QRectF(nX + 10, -ITEM_HEIGHT // 2, pixelsWide,
                              pixelsHigh)

            #设置text颜色
            painter.setPen(Qt.red)
            painter.drawPixmap(nX + 10, -ITEM_HEIGHT // 2, pixelsWide,
                               pixelsHigh, pixmap)  #,
            painter.restore()

            #increment nItemY    item高度设置
            if pixelsHigh <= HEAD_W_H:
                pixelsHigh = HEAD_W_H
                nItemY += pixelsHigh + ITEM_SPACE  #head height + ITEMSPACING
            else:
                nItemY += pixelsHigh + ITEM_SPACE

            #QSize(width(),height)
            #self.sendItemSize.emit(self.width(),pixelsHigh + ITEM_SPACE+30)
            self.sendItemSize.emit(755, pixelsHigh + ITEM_SPACE + 30)

        else:
            painter.save()
            textRect = QRectF(-nWidth // 2 + 59, -ITEM_HEIGHT // 2,
                              pixelsWide + 20, pixelsHigh)
            path.addRoundedRect(textRect, 3, 3)
            path.moveTo(-nWidth // 2 + 59, -ITEM_HEIGHT // 2 + 12)
            path.lineTo(-nWidth // 2 + 49, -ITEM_HEIGHT // 2 + 18)
            path.lineTo(-nWidth // 2 + 59, -ITEM_HEIGHT // 2 + 21)
            painter.setPen(QColor(140, 170, 202))
            painter.drawPath(path)
            painter.restore()

            #绘制头像
            painter.save()
            painter.setPen(Qt.NoPen)
            painter.setBrush(HeaderBgColor)
            leftRect = QRectF(-nWidth // 2 + 5, -ITEM_HEIGHT // 2, HEAD_W_H,
                              HEAD_W_H)
            painter.drawRect(leftRect)
            painter.setPen(HeaderTextColor)

            image = QImage()
            image.loadFromData(self.head)
            painter.drawPixmap(-nWidth // 2 + 5, -ITEM_HEIGHT // 2, HEAD_W_H,
                               HEAD_W_H, QPixmap.fromImage(image))
            painter.restore()

            painter.setPen(COLOR_BLACK)

            textRect = QRectF(-nWidth // 2 + 59 + 10, -ITEM_HEIGHT // 2,
                              pixelsWide, pixelsHigh)

            #设置text颜色
            painter.setPen(Qt.red)
            painter.drawPixmap(-nWidth // 2 + 59 + 10, -ITEM_HEIGHT // 2,
                               pixelsWide, pixelsHigh, pixmap)  #,
            painter.restore()

            #increment nItemY    item高度设置
            if pixelsHigh <= HEAD_W_H:
                pixelsHigh = HEAD_W_H
                nItemY += pixelsHigh + ITEM_SPACE  #head height + ITEMSPACING
            else:
                nItemY += pixelsHigh + ITEM_SPACE

            #QSize(width(),height)
            #self.sendItemSize.emit(self.width(),pixelsHigh + ITEM_SPACE+30)
            self.sendItemSize.emit(755, pixelsHigh + ITEM_SPACE + 30)
Ejemplo n.º 31
0
class RectItem(BaseItem):
    def __init__(self, model_item=None, prefix="", parent=None):
        BaseItem.__init__(self, model_item, prefix, parent)

        self._rect = None
        self._resize = False
        self._resize_start = None
        self._resize_start_rect = None
        self._upper_half_clicked = None
        self._left_half_clicked = None

        self._updateRect(self._dataToRect(self._model_item))
        LOG.debug("Constructed rect %s for model item %s" %
                  (self._rect, model_item))

    def __call__(self, model_item=None, parent=None):
        item = RectItem(model_item, parent)
        item.setPen(self.pen())
        item.setBrush(self.brush())
        return item

    def _dataToRect(self, model_item):
        if model_item is None:
            return QRectF()

        try:
            return QRectF(float(model_item[self.prefix() + 'x']),
                          float(model_item[self.prefix() + 'y']),
                          float(model_item[self.prefix() + 'width']),
                          float(model_item[self.prefix() + 'height']))
        except KeyError as e:
            LOG.debug("RectItem: Could not find expected key in item: " +
                      str(e) + ". Check your config!")
            self.setValid(False)
            return QRectF()

    def _updateRect(self, rect):
        if rect == self._rect:
            return

        self.prepareGeometryChange()
        self._rect = rect
        self.setPos(rect.topLeft())

    def updateModel(self):
        self._rect = QRectF(self.scenePos(), self._rect.size())
        self._model_item.update({
            self.prefix() + 'x':
            float(self._rect.topLeft().x()),
            self.prefix() + 'y':
            float(self._rect.topLeft().y()),
            self.prefix() + 'width':
            float(self._rect.width()),
            self.prefix() + 'height':
            float(self._rect.height()),
        })

    def boundingRect(self):
        return QRectF(QPointF(0, 0), self._rect.size())

    def paint(self, painter, option, widget=None):
        BaseItem.paint(self, painter, option, widget)

        pen = self.pen()
        if self.isSelected():
            pen.setStyle(Qt.DashLine)
        painter.setPen(pen)
        painter.drawRect(self.boundingRect())

    def dataChange(self):
        rect = self._dataToRect(self._model_item)
        self._updateRect(rect)

    def mousePressEvent(self, event):
        #if event.modifiers() & Qt.ControlModifier != 0:
        if event.button() & Qt.RightButton != 0:
            self._resize = True
            self._resize_start = event.scenePos()
            self._resize_start_rect = QRectF(self._rect)
            self._upper_half_clicked = (event.scenePos().y() <
                                        self._resize_start_rect.center().y())
            self._left_half_clicked = (event.scenePos().x() <
                                       self._resize_start_rect.center().x())
            event.accept()
        else:
            BaseItem.mousePressEvent(self, event)

    def mouseMoveEvent(self, event):
        if self._resize:
            diff = event.scenePos() - self._resize_start
            if self._left_half_clicked:
                x = self._resize_start_rect.x() + diff.x()
                w = self._resize_start_rect.width() - diff.x()
            else:
                x = self._resize_start_rect.x()
                w = self._resize_start_rect.width() + diff.x()

            if self._upper_half_clicked:
                y = self._resize_start_rect.y() + diff.y()
                h = self._resize_start_rect.height() - diff.y()
            else:
                y = self._resize_start_rect.y()
                h = self._resize_start_rect.height() + diff.y()

            rect = QRectF(QPointF(x, y), QSizeF(w, h)).normalized()

            self._updateRect(rect)
            self.updateModel()
            event.accept()
        else:
            BaseItem.mouseMoveEvent(self, event)

    def mouseReleaseEvent(self, event):
        if self._resize:
            self._resize = False
            event.accept()
        else:
            BaseItem.mouseReleaseEvent(self, event)

    def keyPressEvent(self, event):
        BaseItem.keyPressEvent(self, event)
        step = 1
        if event.modifiers() & Qt.ShiftModifier:
            step = 5
        ds = {
            Qt.Key_Left: (-step, 0),
            Qt.Key_Right: (step, 0),
            Qt.Key_Up: (0, -step),
            Qt.Key_Down: (0, step),
        }.get(event.key(), None)
        if ds is not None:
            if event.modifiers() & Qt.ControlModifier:
                rect = self._rect.adjusted(*((0, 0) + ds))
            else:
                rect = self._rect.adjusted(*(ds + ds))
            self._updateRect(rect)
            self.updateModel()
            event.accept()
Ejemplo n.º 32
0
    def drawMagnifier(self):
        # First, calculate the magnifier position due to the mouse position
        watchAreaWidth = 16
        watchAreaHeight = 16
        watchAreaPixmap = QPixmap()

        cursor_pos = self.mousePoint

        watchArea = QRect(
            QPoint(cursor_pos.x() - watchAreaWidth / 2,
                   cursor_pos.y() - watchAreaHeight / 2),
            QPoint(cursor_pos.x() + watchAreaWidth / 2,
                   cursor_pos.y() + watchAreaHeight / 2))
        if watchArea.left() < 0:
            watchArea.moveLeft(0)
            watchArea.moveRight(watchAreaWidth)
        if self.mousePoint.x() + watchAreaWidth / 2 >= self.screenPixel.width(
        ):
            watchArea.moveRight(self.screenPixel.width() - 1)
            watchArea.moveLeft(watchArea.right() - watchAreaWidth)
        if self.mousePoint.y() - watchAreaHeight / 2 < 0:
            watchArea.moveTop(0)
            watchArea.moveBottom(watchAreaHeight)
        if self.mousePoint.y(
        ) + watchAreaHeight / 2 >= self.screenPixel.height():
            watchArea.moveBottom(self.screenPixel.height() - 1)
            watchArea.moveTop(watchArea.bottom() - watchAreaHeight)

        # tricks to solve the hidpi impact on QCursor.pos()
        watchArea.setTopLeft(
            QPoint(watchArea.topLeft().x() * self.scale,
                   watchArea.topLeft().y() * self.scale))
        watchArea.setBottomRight(
            QPoint(watchArea.bottomRight().x() * self.scale,
                   watchArea.bottomRight().y() * self.scale))
        watchAreaPixmap = self.screenPixel.copy(watchArea)

        # second, calculate the magnifier area
        magnifierAreaWidth = watchAreaWidth * 10
        magnifierAreaHeight = watchAreaHeight * 10
        fontAreaHeight = 40

        cursorSize = 24
        magnifierArea = QRectF(
            QPoint(QCursor.pos().x() + cursorSize,
                   QCursor.pos().y() + cursorSize),
            QPoint(QCursor.pos().x() + cursorSize + magnifierAreaWidth,
                   QCursor.pos().y() + cursorSize + magnifierAreaHeight))
        if magnifierArea.right() >= self.screenPixel.width():
            magnifierArea.moveLeft(QCursor.pos().x() - magnifierAreaWidth -
                                   cursorSize / 2)
        if magnifierArea.bottom() + fontAreaHeight >= self.screenPixel.height(
        ):
            magnifierArea.moveTop(QCursor.pos().y() - magnifierAreaHeight -
                                  cursorSize / 2 - fontAreaHeight)

        # third, draw the watch area to magnifier area
        watchAreaScaled = watchAreaPixmap.scaled(
            QSize(magnifierAreaWidth * self.scale,
                  magnifierAreaHeight * self.scale))
        magnifierPixmap = self.graphicsScene.addPixmap(watchAreaScaled)
        magnifierPixmap.setOffset(magnifierArea.topLeft())

        # then draw lines and text
        self.graphicsScene.addRect(QRectF(magnifierArea),
                                   QPen(QColor(255, 255, 255), 2))
        self.graphicsScene.addLine(
            QLineF(QPointF(magnifierArea.center().x(), magnifierArea.top()),
                   QPointF(magnifierArea.center().x(),
                           magnifierArea.bottom())),
            QPen(QColor(0, 255, 255), 2))
        self.graphicsScene.addLine(
            QLineF(QPointF(magnifierArea.left(),
                           magnifierArea.center().y()),
                   QPointF(magnifierArea.right(),
                           magnifierArea.center().y())),
            QPen(QColor(0, 255, 255), 2))

        # get the rgb of mouse point
        pointRgb = QColor(self.screenPixel.toImage().pixel(self.mousePoint))

        # draw information
        self.graphicsScene.addRect(
            QRectF(
                magnifierArea.bottomLeft(),
                magnifierArea.bottomRight() + QPoint(0, fontAreaHeight + 30)),
            Qt.black, QBrush(Qt.black))
        rgbInfo = self.graphicsScene.addSimpleText(
            ' Rgb: ({0}, {1}, {2})'.format(pointRgb.red(), pointRgb.green(),
                                           pointRgb.blue()))
        rgbInfo.setPos(magnifierArea.bottomLeft() + QPoint(0, 5))
        rgbInfo.setPen(QPen(QColor(255, 255, 255), 2))

        rect = self.selectedArea.normalized()
        sizeInfo = self.graphicsScene.addSimpleText(' Size: {0} x {1}'.format(
            rect.width() * self.scale,
            rect.height() * self.scale))
        sizeInfo.setPos(magnifierArea.bottomLeft() + QPoint(0, 15) +
                        QPoint(0, fontAreaHeight / 2))
        sizeInfo.setPen(QPen(QColor(255, 255, 255), 2))
Ejemplo n.º 33
0
    def drawControl(self, p, opt, arect, icon, menustyle):
        """
        due to overrides the "paintEvent" method, so we must repaint all menu item by self.
        luckly, we have qt source code to reference.

        void drawControl (ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *w=0) const
        https://cep.xray.aps.anl.gov/software/qt4-x11-4.8.6-browser/df/d91/class_q_style_sheet_style.html#ab92c0e0406eae9a15bc126b67f88c110
        Line 3533: element = CE_MenuItem
        """

        style = self.style()
        p.setPen(menustyle.getPenColor(opt))

        # Line 3566: draw icon and checked sign
        checkable = opt.checkType != QStyleOptionMenuItem.NotCheckable
        checked = opt.checked if checkable else False
        if opt.icon.isNull() is False:  # has custom icon
            dis = not (int(opt.state) & int(QStyle.State_Enabled))
            active = int(opt.state) & int(QStyle.State_Selected)
            mode = QIcon.Disabled if dis else QIcon.Normal
            if active != 0 and not dis: mode = QIcon.Active

            fw = style.pixelMetric(QStyle.PM_MenuPanelWidth, opt, self)
            icone = style.pixelMetric(QStyle.PM_SmallIconSize, opt, self)
            iconRect = QRectF(arect.x() - fw, arect.y(), self._side_image.width(), arect.height())
            if checked:
                pixmap = icon.pixmap(QSize(icone, icone), mode, QIcon.On)
            else:
                pixmap = icon.pixmap(QSize(icone, icone), mode)

            pixw = pixmap.width()
            pixh = pixmap.height()
            pmr = QRectF(0, 0, pixw, pixh)
            pmr.moveCenter(iconRect.center())

            if checked: p.drawRect(QRectF(pmr.x() - 1, pmr.y() - 1, pixw + 2, pixh + 2))
            p.drawPixmap(pmr.topLeft(), pixmap)

        elif checkable and checked:  # draw default checked sign
            opt.rect = QRect(0, arect.y(), self._side_image.width(), arect.height())
            opt.palette.setColor(QPalette.Text, menustyle.getPenColor(opt))
            style.drawPrimitive(QStyle.PE_IndicatorMenuCheckMark, opt, p, self)

        # Line 3604: draw emnu text
        font = menustyle.font
        if font is not None:
            p.setFont(font)
        else:
            p.setFont(opt.font)
        text_flag = Qt.AlignVCenter | Qt.TextShowMnemonic | Qt.TextDontClip | Qt.TextSingleLine

        tr = QRect(arect)
        s = opt.text
        if '\t' in s:
            ss = s[s.index('\t') + 1:]
            fontwidth = opt.fontMetrics.width(ss)
            tr.moveLeft(opt.rect.right() - fontwidth)
            tr = QStyle.visualRect(opt.direction, opt.rect, tr)
            p.drawText(tr, text_flag, ss)
        tr.moveLeft(self._side_image.width() + arect.x())
        tr = QStyle.visualRect(opt.direction, opt.rect, tr)
        p.drawText(tr, text_flag, s)

        # Line 3622: draw sub menu arrow
        if opt.menuItemType == QStyleOptionMenuItem.SubMenu:
            arrowW = style.pixelMetric(QStyle.PM_IndicatorWidth, opt, self)
            arrowH = style.pixelMetric(QStyle.PM_IndicatorHeight, opt, self)
            arrowRect = QRect(0, 0, arrowW, arrowH)
            arrowRect.moveBottomRight(arect.bottomRight())
            arrow = QStyle.PE_IndicatorArrowLeft if opt.direction == Qt.RightToLeft else QStyle.PE_IndicatorArrowRight

            opt.rect = arrowRect
            opt.palette.setColor(QPalette.ButtonText, menustyle.getPenColor(opt))
            style.drawPrimitive(arrow, opt, p, self)
        pass
Ejemplo n.º 34
0
Archivo: deusex.py Proyecto: hodoje/dcs
class DeusEx(QGraphicsObject):
    deusExActivateSignal = pyqtSignal(DeusExSignalData)

    def __init__(self, config, type, pulseSound, endingSound):
        super().__init__()
        self.type = type
        self.config = config
        self.width = 200
        self.height = 200
        self.m_boundingRect = QRectF(0, 0, self.width, self.height)
        self.m_painterPath = QPainterPath()
        self.m_painterPath.addEllipse(self.m_boundingRect)
        # radial gradient settings
        self.rgcx = self.m_boundingRect.center().x()
        self.rgcy = self.m_boundingRect.center().y()
        self.rgMinRadius = 50
        self.rgMaxRadius = 300
        self.rgCurrentRadius = 50
        self.rgfx = self.rgcx
        self.rgfy = self.rgcy
        self.rg = QRadialGradient(self.rgcx, self.rgcy, self.rgCurrentRadius, self.rgfx, self.rgfy)
        if self.type is DeusExTypes.POSITIVE:
            firstClr = QColor(Qt.green)
            firstClr.setAlphaF(0.7)
            secondClr = QColor(Qt.darkGreen)
            secondClr.setAlphaF(0.7)
            self.rg.setColorAt(0.0, firstClr)
            self.rg.setColorAt(1.0, secondClr)
        else:
            firstClr = QColor(Qt.red)
            firstClr.setAlphaF(0.7)
            secondClr = QColor(Qt.darkRed)
            secondClr.setAlphaF(0.7)
            self.rg.setColorAt(0.0, firstClr)
            self.rg.setColorAt(1.0, secondClr)
        # pulsing sound
        self.pulseSound = pulseSound
        self.endingSound = endingSound
        # pulsing timer
        self.pulseTimer = QTimer()
        self.pulseTimer.setTimerType(Qt.PreciseTimer)
        self.pulseTimer.timeout.connect(self.pulse)
        self.pulseTimer.start(100)
        # pre activate timer
        self.preActivateTimer = QTimer()
        self.preActivateTimer.setTimerType(Qt.PreciseTimer)
        self.preActivateTimer.timeout.connect(self.preActivate)
        if self.type is DeusExTypes.POSITIVE:
            self.preActivateTimer.start(10000)
        else:
            self.preActivateTimer.start(3000)
        # activate timer
        self.activateTimer = QTimer()
        self.activateTimer.setTimerType(Qt.PreciseTimer)
        self.activateTimer.timeout.connect(self.endingSoundFinished)

    def boundingRect(self):
        return self.m_boundingRect

    def shape(self):
        return self.m_painterPath

    def paint(self, QPainter, QStyleOptionGraphicsItem, widget=None):
        pen = QPen()
        if self.type is DeusExTypes.POSITIVE:
            pen.setColor(Qt.darkGreen)
        else:
            pen.setColor(Qt.darkRed)
        brush = QBrush(self.rg)
        QPainter.setPen(pen)
        QPainter.setBrush(brush)
        QPainter.drawEllipse(self.m_boundingRect)

    def pulse(self):
        if self.rgCurrentRadius == 50:
            self.pulseSound.play()
        self.rgCurrentRadius += 20
        self.rg.setCenterRadius(self.rgCurrentRadius)
        if self.rgCurrentRadius >= self.rgMaxRadius:
            self.rgCurrentRadius = self.rgMinRadius

    def preActivate(self):
        firstClr = QColor(Qt.yellow)
        firstClr.setAlphaF(0.7)
        secondClr = QColor(Qt.darkYellow)
        secondClr.setAlphaF(0.7)
        self.rg.setColorAt(0.0, firstClr)
        self.rg.setColorAt(1.0, secondClr)
        self.pulseSound.stop()
        self.pulseTimer.timeout.disconnect()
        self.preActivateTimer.timeout.disconnect()
        self.pulseTimer.stop()
        self.preActivateTimer.stop()

        # activate
        self.endingSound.play()
        self.activateTimer.start()

    def endingSoundFinished(self):
        if self.endingSound.get_state() == AL_STOPPED:
            deusExSignalData = DeusExSignalData(self.type)
            for obj in self.collidingItems():
                if type(obj).__name__ == "Player":
                    deusExSignalData.markedPlayers.append(obj)
            self.activateTimer.timeout.disconnect()
            self.activateTimer.stop()
            self.deusExActivateSignal.emit(deusExSignalData)
            self.scene().removeItem(self)
            del self