コード例 #1
0
ファイル: preview.py プロジェクト: yaoxinyuan/Pyslvs-UI
    def __draw_link(self, name: str, points: Sequence[int]) -> None:
        """Draw link function.

        The link color will be the default color.
        """
        pen = QPen(Qt.black if self.monochrome else color_qt('blue'))
        pen.setWidth(self.link_width)
        self.painter.setPen(pen)
        brush = color_qt('dark-gray') if self.monochrome else LINK_COLOR
        brush.setAlphaF(0.70)
        self.painter.setBrush(brush)
        qpoints = tuple(
            QPointF(self.pos[i][0], -self.pos[i][1]) * self.zoom
            for i in points if self.pos[i] and (not isnan(self.pos[i][0]))
        )
        if len(qpoints) == len(points):
            self.painter.drawPolygon(*qpoints)
        self.painter.setBrush(Qt.NoBrush)
        if self.show_point_mark and name != VLink.FRAME and qpoints:
            pen.setColor(Qt.darkGray)
            self.painter.setPen(pen)
            self.painter.setFont(QFont('Arial', self.font_size))
            cen_x = sum(self.pos[i][0] for i in points if self.pos[i])
            cen_y = sum(self.pos[i][1] for i in points if self.pos[i])
            self.painter.drawText(
                QPointF(cen_x, -cen_y) * self.zoom / len(points),
                f"[{name}]"
            )
コード例 #2
0
    def plot(self, data, index=None, label=None, color=QColor(Qt.red)):
        """ Sets the charts data points.

        :param data: ordinate values
        :param index: abscissa values. Optional, if not set datapoints are indexed starting with 0
        :param label: Label of the chart_tests.
        :param color: Color of the chart_tests
        """
        self._yData = data

        if index is not None:
            self._xData = index
        else:
            self._xData = np.arange(len(data))

        if label is not None:
            self._label = label

        self._color = color

        self._bRect = QRectF(
            QPointF(np.min(self._xData), np.min(self._yData)),
            QPointF(np.max(self._xData), np.max(self._yData)),
        )
        # _log.debug("Plot BB: {}".format(self._bRect))
        #
        # # TODO: Public access
        # self.canvas._items.append(self._bRect)

        self._makePath()
コード例 #3
0
    def paintEvent(self, a0: QPaintEvent) -> None:
        super().paintEvent(a0)
        painter = QPainter(self)
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        rect = QRectF(self.margin, self.margin,
                      self.width() - self.margin * 2,
                      self.height() - 2 * self.margin)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawEllipse(rect)

        painter.restore()
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen()
        pen.setWidth(2)
        painter.setPen(pen)
        mid_point = QPointF(a0.rect().width() / 2, a0.rect().height() / 2)
        radius = min(a0.rect().height(), a0.rect().width()) / 3
        rays_num = 10
        for i in range(rays_num):
            point = QPointF(
                math.sin(math.pi / (rays_num / 2) * i) * radius,
                math.cos(math.pi / (rays_num / 2) * i) * radius)
            painter.drawLine(mid_point + (point * 0.4), mid_point + point)
        painter.restore()
コード例 #4
0
 def catch(exprs: Sequence[str]) -> bool:
     """Detection function for solution polygons."""
     points, _ = self.solution_polygon(
         exprs[0],
         exprs[1:-1],
         exprs[-1],
         self.vpoints
     )
     if len(points) < 3:
         points = convex_hull(
             [(x + self.sr, y + self.sr) for x, y in points]
             + [(x - self.sr, y - self.sr) for x, y in points],
             as_qpoint=True
         )
     else:
         points = [QPointF(x, y) for x, y in points]
     polygon = QPolygonF(points)
     if rect:
         return polygon.intersects(
             QPolygonF(self.selector.to_rect(self.zoom)))
     else:
         return polygon.containsPoint(
             QPointF(self.selector.x, -self.selector.y) * self.zoom,
             Qt.WindingFill
         )
コード例 #5
0
    def paint(self, p, opt, widget):

        # Enforce constraints on handles
        r2 = Point(np.cos(np.radians(self.thetacenter)),
                   np.sin(np.radians(self.thetacenter)))  # chi center direction vector
        # constrain innerhandle to be parallel to outerhandle, and shorter than outerhandle
        self.innerhandle.setPos(r2 * self.innerradius)
        # constrain widthhandle to be counter-clockwise from innerhandle
        widthangle = np.radians(self.thetawidth / 2 + self.thetacenter)
        widthv = Point(np.cos(widthangle), np.sin(widthangle)) if self.thetawidth > 0 else r2
        # constrain widthhandle to half way between inner and outerhandles
        self.widthhandle.setPos(widthv * (self.innerradius + self.outerradius) / 2)
        # constrain handles to base values
        self.outerhandle.setPos(r2 * self.outerradius)


        pen = self.currentPen
        pen.setColor(QColor(0, 255, 255))

        p.setPen(pen)

        r = self.boundingRect()
        # p.drawRect(r)
        p.setRenderHint(QPainter.Antialiasing)

        p.scale(r.width(), r.height())  # workaround for GL bug

        centerangle = self.innerhandle.pos().angle(Point(1, 0))
        startangle = centerangle - self.thetawidth / 2
        endangle = centerangle + self.thetawidth / 2

        r = QCircRectF(radius=0.5)
        if self.innerradius < self.outerradius and self.thetawidth > 0:
            p.drawArc(r, -startangle * 16, -self.thetawidth * 16)

        radius = self.innerradius / self.outerradius / 2
        r = QCircRectF()
        r.radius = radius

        if self.innerradius < self.outerradius and self.thetawidth > 0:
            p.drawArc(r, -startangle * 16, -self.thetawidth * 16)

        pen.setStyle(Qt.DashLine)
        p.setPen(pen)

        p.drawLine(QPointF(0., 0.), self.widthhandle.pos().norm() / 2)
        r1v = self.innerhandle.pos().norm()
        p.drawLine(QPointF(0., 0.),
                   (-1. * self.widthhandle.pos() + 2 * self.widthhandle.pos().dot(r1v) * r1v).norm() / 2)
        pen.setStyle(Qt.SolidLine)

        if self.innerradius < self.outerradius and self.thetawidth > 0:
            path = QPainterPath()
            path.moveTo((-1. * self.widthhandle.pos() + 2 * self.widthhandle.pos().dot(r1v) * r1v).norm() / 2)
            path.arcTo(r, -startangle, -self.thetawidth)  # inside
            path.lineTo(self.widthhandle.pos().norm() / 2)  # ? side
            path.arcTo(QCircRectF(radius=0.5), -endangle, self.thetawidth)  # outside
            path.lineTo((-1. * self.widthhandle.pos() + 2 * self.widthhandle.pos().dot(r1v) * r1v).norm() / 2)
            self.path = path
            p.fillPath(path, QBrush(QColor(0, 255, 255, 20)))
コード例 #6
0
ファイル: pcombobox.py プロジェクト: ReactDev-099/Python-UI
    def paintEvent(self, event):

        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing)
        if self.label_width <= 0:
            return

        painter.setPen(Qt.NoPen)
        if self.hover:
            painter.setBrush(
                QColor(self.back_color.red() + 30,
                       self.back_color.green() + 30,
                       self.back_color.blue() + 30))
        else:
            painter.setBrush(self.back_color)

        painter.drawRoundedRect(QRect(0, 0, self.width(), self.height()),
                                self.border_radius, self.border_radius)

        x1 = QPointF(self.label_width + float(self.height() / 3),
                     float(self.height() * 0.45))
        x2 = QPointF(
            self.label_width + float(self.height() * (0.66 + self.rate) / 2),
            float(self.height() * 0.55))
        x3 = QPointF(self.width() - float(self.height() / 3),
                     float(self.height() * 0.45))

        check_path = QPainterPath()
        check_path.moveTo(x1)
        check_path.lineTo(x2)
        check_path.lineTo(x3)

        pen = QPen(self.text_color, self.drop_thick, Qt.SolidLine)
        painter.setPen(pen)
        painter.drawPath(check_path)
コード例 #7
0
    def setData(self, data):

        xvals = data.coords[data.dims[-1]]
        yvals = data.coords[data.dims[-2]]
        xmin = float(xvals.min())
        xmax = float(xvals.max())
        ymin = float(yvals.min())
        ymax = float(yvals.max())

        # Position the image according to coords
        shape = data.shape
        a = [(0, shape[-1]), (shape[-2] - 1, shape[-1]), (shape[-2] - 1, 1), (0, 1)]

        # b = [(ymin, xmax), (ymax, xmax), (ymax, xmin), (ymin, xmin)]
        b = [(xmax, ymin), (xmax, ymax), (xmin, ymax), (xmin, ymin)]

        quad1 = QPolygonF()
        quad2 = QPolygonF()
        for p, q in zip(a, b):
            quad1.append(QPointF(*p))
            quad2.append(QPointF(*q))

        transform = QTransform()
        QTransform.quadToQuad(quad1, quad2, transform)

        # Bind coords from the xarray to the timeline axis
        # super(SliceableGraphicsView, self).setImage(img, autoRange, autoLevels, levels, axes, np.asarray(img.coords[img.dims[0]]), pos, scale, transform, autoHistogramRange, levelMode)
        self.image_item.setImage(np.asarray(data), autoLevels=False)
        self.image_item.setTransform(transform)

        # Label the image axes
        self.view.setLabel('left', data.dims[-2])
        self.view.setLabel('bottom', data.dims[-1])
コード例 #8
0
    def toShape(self, ifClean=True):
        shapes = []
        if len(self.col_lines) != 0 and len(self.row_lines) != 0:

            def createRectangle(p0, p1):
                shape = Shape()
                shape.shape_type = "rectangle"
                shape.addPoint(p0)
                shape.addPoint(p1)
                shape.close()
                return shape

            offset_x = self.box['xmin']
            offset_y = self.box['ymin']

            # for i in range(0, len(self.row_lines), 2):
            for i in range(0, len(self.row_lines), 2):
                for j in range(0, len(self.col_lines), 2):
                    topLeft = QPointF(
                        self.col_lines[j].points[0].x() + offset_x,
                        self.row_lines[i].points[0].y() + offset_y)
                    bottomRight = QPointF(
                        self.col_lines[j + 1].points[0].x() + offset_x,
                        self.row_lines[i + 1].points[0].y() + offset_y)
                    shape = createRectangle(
                        topLeft,
                        bottomRight,
                    )
                    if not shape.isWhiteRect(self.np_image):
                        shapes.append(shape)

        if ifClean:
            self.clean()
        return shapes
コード例 #9
0
    def intersectingEdges(point1, point2, points):
        """Find intersecting edges.

        For each edge formed by `points', yield the intersection
        with the line segment `(x1,y1) - (x2,y2)`, if it exists.
        Also return the distance of `(x2,y2)' to the middle of the
        edge along with its index, so that the one closest can be chosen.
        """
        (x1, y1) = point1
        (x2, y2) = point2
        for i in range(4):
            x3, y3 = points[i]
            x4, y4 = points[(i + 1) % 4]
            denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
            nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
            nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
            if denom == 0:
                # This covers two cases:
                #   nua == nub == 0: Coincident
                #   otherwise: Parallel
                continue
            ua, ub = nua / denom, nub / denom
            if 0 <= ua <= 1 and 0 <= ub <= 1:
                x = x1 + ua * (x2 - x1)
                y = y1 + ua * (y2 - y1)
                m = QPointF((x3 + x4) / 2, (y3 + y4) / 2)
                d = distance(m - QPointF(x2, y2))
                yield d, i, (x, y)
コード例 #10
0
    def transform(self, img=None):
        if not self._geometry or not self.displaymode == DisplayMode.remesh:
            return super(EwaldCorrected, self).transform(
                img)  # Do pixel space transform when not calibrated

        from camsaxs import remesh_bbox

        img, q_x, q_z = remesh_bbox.remesh(np.squeeze(img),
                                           self._geometry,
                                           reflection=False,
                                           alphai=None)

        # Build Quads
        shape = img.shape
        a = shape[-2] - 1, 0  # bottom-left
        b = shape[-2] - 1, shape[-1] - 1  # bottom-right
        c = 0, shape[-1] - 1  # top-right
        d = 0, 0  # top-left

        quad1 = QPolygonF()
        quad2 = QPolygonF()
        for p, q in zip([a, b, c, d],
                        [a, b, c, d]):  # the zip does the flip :P
            quad1.append(QPointF(*p[::-1]))
            quad2.append(QPointF(q_x[q], q_z[q]))

        transform = QTransform()
        QTransform.quadToQuad(quad1, quad2, transform)

        for item in self.view.items:
            if isinstance(item, ImageItem):
                item.setTransform(transform)
        self._transform = transform

        return img, self._transform
コード例 #11
0
    def closePolyline(self, painter, xMap, yMap, polygon):
        """
        Complete a polygon to be a closed polygon including the
        area between the original polygon and the baseline.

        :param QPainter painter: Painter
        :param qwt.scale_map.QwtScaleMap xMap: Maps x-values into pixel coordinates.
        :param qwt.scale_map.QwtScaleMap yMap: Maps y-values into pixel coordinates.
        :param QPolygonF polygon: Polygon to be completed
        """
        if polygon.size() < 2:
            return
        baseline = self.__data.baseline
        if self.orientation() == Qt.Horizontal:
            if yMap.transformation():
                baseline = yMap.transformation().bounded(baseline)
            refY = yMap.transform(baseline)
            polygon.append(QPointF(polygon.last().x(), refY))
            polygon.append(QPointF(polygon.first().x(), refY))
        else:
            if xMap.transformation():
                baseline = xMap.transformation().bounded(baseline)
            refX = xMap.transform(baseline)
            polygon.append(QPointF(refX, polygon.last().y()))
            polygon.append(QPointF(refX, polygon.first().y()))
コード例 #12
0
 def paintEvent(self, event: QPaintEvent):
     painter = QPainter(self)
     painter.save()
     painter.setRenderHint(QPainter.Antialiasing)
     size = min(self.width(), self.height())
     rect = QRect(0, 0, size, size)
     painter.setBrush(self.background_color)
     painter.setPen(self.background_color)
     painter.drawEllipse(rect)
     painter.setBrush(self.main_color)
     painter.setPen(self.main_color)
     factor = self.nominator / self.denominator
     radius = size / 2
     if factor > 0.5:
         painter.drawChord(rect, 0, 16 * 360 * 0.5)
         painter.drawChord(rect, 16 * 180, 16 * 360 * (factor - 0.5))
         zero_point = QPointF(0, radius)
     else:
         painter.drawChord(rect, 0, 16 * 360 * factor)
         zero_point = QPointF(size, radius)
     mid_point = QPointF(radius, radius)
     point = mid_point + QPointF(
         math.cos(math.pi * (factor * 2)) * radius, -math.sin(math.pi * (factor * 2)) * radius
     )
     polygon = QPolygonF()
     polygon += mid_point
     polygon += zero_point
     polygon += point
     painter.drawPolygon(polygon)
     painter.restore()
コード例 #13
0
def get_plot_x_section(obj, apply_lut=False):
    """
    Return plot cross section along x-axis,
    at the y value defined by 'obj', a Marker/AnnotatedPoint object
    """
    _x0, y0 = get_object_coordinates(obj)
    plot = obj.plot()
    xmap = plot.canvasMap(plot.X_BOTTOM)
    xc0, xc1 = xmap.p1(), xmap.p2()
    _xc0, yc0 = axes_to_canvas(obj, 0, y0)
    if plot.get_axis_direction("left"):
        yc1 = yc0 + 1
    else:
        yc1 = yc0 - 3
    try:
        # TODO: eventually add an option to apply interpolation algorithm
        data = get_image_from_qrect(
            plot,
            QPointF(xc0, yc0),
            QPointF(xc1, yc1),
            apply_lut=apply_lut,
            add_images=True,
            apply_interpolation=False,
        )
    except (ValueError, ZeroDivisionError, TypeError):
        return np.array([]), np.array([])
    y = data.mean(axis=0)
    x0, _y0 = canvas_to_axes(obj, QPointF(xc0, yc0))
    x1, _y1 = canvas_to_axes(obj, QPointF(xc1, yc1))
    x = np.linspace(x0, x1, len(y))
    return x, y
コード例 #14
0
ファイル: node_geometry.py プロジェクト: Tyrant-K/ICTFE
    def widget_position(self) -> QPointF:
        """
        Returns the position of a widget on the Node surface

        Returns
        -------
        value : QPointF
        """
        widget = self._model.embedded_widget()
        if not widget:
            return QPointF()

        if widget.sizePolicy().verticalPolicy() & QSizePolicy.ExpandFlag:
            # If the widget wants to use as much vertical space as possible,
            # place it immediately after the caption.
            return QPointF(self._spacing + self.port_width(PortType.input),
                           self.caption_height)

        if self._model.validation_state() != NodeValidationState.valid:
            return QPointF(
                self._spacing + self.port_width(PortType.input),
                (self.caption_height + self._height - self.validation_height -
                 self._spacing - widget.height()) / 2.0,
            )

        return QPointF(self._spacing + self.port_width(PortType.input),
                       (self.caption_height + self._height - widget.height()) /
                       2.0)
コード例 #15
0
ファイル: annotation.py プロジェクト: migueldvb/specviz
    def paint(self, p, *args):
        ''' Overrides the default implementation so as
            to draw a vertical marker.
        '''
        # draw the text
        super(LineIDMarker, self).paint(p, args)

        # Add marker. Geometry depends on the
        # text being vertical or horizontal.
        points = []
        bounding_rect = self.boundingRect()

        if self._orientation == 'vertical':
            x = bounding_rect.x()
            y = bounding_rect.y() + bounding_rect.height() / 2.

            points.append(QPointF(x, y))
            points.append(QPointF(x - 20, y))
        else:
            x = bounding_rect.x() + bounding_rect.width() / 2.
            y = bounding_rect.y() + bounding_rect.height() * 2.

            points.append(QPointF(x, y))
            points.append(QPointF(x, y - 20))

        polygon = QPolygonF(points)

        pen = QPen(QColor(functions.mkColor(self._color)))
        p.setPen(pen)
        p.drawPolygon(polygon)
コード例 #16
0
 def draw_slvs_ranges(self) -> None:
     """Draw solving range."""
     pen = QPen()
     pen.setWidth(5)
     for i, (tag, rect) in enumerate(self.ranges.items()):
         range_color = QColor(color_num(i + 1))
         range_color.setAlpha(30)
         self.painter.setBrush(range_color)
         range_color.setAlpha(255)
         pen.setColor(range_color)
         self.painter.setPen(pen)
         cx = rect.x() * self.zoom
         cy = rect.y() * -self.zoom
         if rect.width():
             self.painter.drawRect(QRectF(
                 QPointF(cx, cy),
                 QSizeF(rect.width(), rect.height()) * self.zoom
             ))
         else:
             self.draw_circle(QPointF(cx, cy), 3)
         range_color.setAlpha(255)
         pen.setColor(range_color)
         self.painter.setPen(pen)
         self.painter.drawText(QPointF(cx, cy) + QPointF(6, -6), tag)
         self.painter.setBrush(Qt.NoBrush)
コード例 #17
0
 def draw_icon(self, painter):
     pen = painter.pen()
     pen.setWidthF(pen.width()*2)
     pen.setCapStyle(Qt.FlatCap)
     painter.setPen(pen)
     # Circle parameters
     radius = 0.3
     center = (0.5, 1 - radius)
     # Draw circle
     painter.drawEllipse(QPointF(*center),
                         radius, radius)
     # X pattern
     quad = math.cos(math.radians(45)) * radius
     painter.drawLine(QLineF(center[0] + quad,
                             center[1] + quad,
                             center[0] - quad,
                             center[1] - quad))
     painter.drawLine(QLineF(center[0] + quad,
                             center[1] - quad,
                             center[0] - quad,
                             center[1] + quad))
     # Interlock Icon
     square_dims = (0.4, 0.2)
     painter.drawLine(QPointF(center[0], center[1] - radius),
                      QPointF(center[0], square_dims[1]))
     painter.setBrush(self._interlock_brush)
     painter.drawRect(QRectF((1 - square_dims[0])/2., 0, *square_dims))
コード例 #18
0
    def points_c1_c2(self) -> tuple:
        """
        Connection points (c1, c2)

        Returns
        -------
        c1: QPointF
            The first point
        c2: QPointF
            The second point
        """
        x_distance = self._in.x() - self._out.x()

        default_offset = 200.0
        x_offset = min((default_offset, abs(x_distance)))
        y_offset = 0

        x_ratio = 0.5
        if x_distance <= 0:
            y_distance = self._in.y() - self._out.y() + 20
            y_direction = (-1.0 if y_distance < 0 else 1.0)
            y_offset = y_direction * min((default_offset, abs(y_distance)))
            x_ratio = 1.0

        x_offset *= x_ratio
        return (QPointF(self._out.x() + x_offset,
                        self._out.y() + y_offset),
                QPointF(self._in.x() - x_offset,
                        self._in.y() - y_offset))
コード例 #19
0
def get_plot_average_y_section(obj, apply_lut=False):
    """
    Return cross section along y-axis, averaged on ROI defined by 'obj'
    'obj' is an AbstractShape object supporting the 'get_rect' method
    (RectangleShape, AnnotatedRectangle, etc.)
    """
    x0, y0, x1, y1 = obj.get_rect()
    xc0, yc0 = axes_to_canvas(obj, x0, y0)
    xc1, yc1 = axes_to_canvas(obj, x1, y1)
    invert = False
    ydir = obj.plot().get_axis_direction("left")
    if (ydir and yc0 > yc1) or (not ydir and yc0 < yc1):
        invert = True
        yc1, yc0 = yc0, yc1
    if xc0 > xc1:
        xc1, xc0 = xc0, xc1
    try:
        data = get_image_from_qrect(
            obj.plot(),
            QPointF(xc0, yc0),
            QPointF(xc1, yc1),
            apply_lut=apply_lut,
            apply_interpolation=False,
        )
    except (ValueError, ZeroDivisionError, TypeError):
        return np.array([]), np.array([])
    y = data.mean(axis=1)
    x = np.linspace(y0, y1, len(y))
    if invert:
        x = x[::-1]
    return x, y
コード例 #20
0
def get_plot_y_section(obj, apply_lut=False):
    """
    Return plot cross section along y-axis,
    at the x value defined by 'obj', a Marker/AnnotatedPoint object
    """
    x0, _y0 = get_object_coordinates(obj)
    plot = obj.plot()
    ymap = plot.canvasMap(plot.Y_LEFT)
    yc0, yc1 = ymap.p1(), ymap.p2()
    if plot.get_axis_direction("left"):
        yc1, yc0 = yc0, yc1
    xc0, _yc0 = axes_to_canvas(obj, x0, 0)
    xc1 = xc0 + 1
    try:
        data = get_image_from_qrect(
            plot,
            QPointF(xc0, yc0),
            QPointF(xc1, yc1),
            apply_lut=apply_lut,
            add_images=True,
            apply_interpolation=False,
        )
    except (ValueError, ZeroDivisionError, TypeError):
        return np.array([]), np.array([])
    y = data.mean(axis=1)
    _x0, y0 = canvas_to_axes(obj, QPointF(xc0, yc0))
    _x1, y1 = canvas_to_axes(obj, QPointF(xc1, yc1))
    x = np.linspace(y0, y1, len(y))
    return x, y
コード例 #21
0
    def draw_node_rect(painter: QPainter, geom: NodeGeometry,
                       model: NodeDataModel,
                       graphics_object: NodeGraphicsObject,
                       node_style: NodeStyle):
        """
        Draw node rect

        Parameters
        ----------
        painter : QPainter
        geom : NodeGeometry
        model : NodeDataModel
        graphics_object : NodeGraphicsObject
        node_style : NodeStyle
        """
        color = (node_style.selected_boundary_color
                 if graphics_object.isSelected() else
                 node_style.normal_boundary_color)
        p = QPen(color, (node_style.hovered_pen_width
                         if geom.hovered else node_style.pen_width))
        painter.setPen(p)

        gradient = QLinearGradient(QPointF(0.0, 0.0),
                                   QPointF(2.0, geom.height))
        for at_, color in node_style.gradient_colors:
            gradient.setColorAt(at_, color)
        painter.setBrush(gradient)

        diam = node_style.connection_point_diameter
        boundary = QRectF(-diam, -diam, 2.0 * diam + geom.width,
                          2.0 * diam + geom.height)
        radius = 3.0
        painter.drawRoundedRect(boundary, radius, radius)
コード例 #22
0
ファイル: node_geometry.py プロジェクト: Tyrant-K/ICTFE
    def port_scene_position(self,
                            port_type: PortType,
                            index: int,
                            t: QTransform = None) -> QPointF:
        """
        Port scene position

        Parameters
        ----------
        port_type : PortType
        index : int
        t : QTransform

        Returns
        -------
        value : QPointF
        """
        if t is None:
            t = QTransform()

        step = self._entry_height + self._spacing
        total_height = float(self.caption_height) + step * index
        # TODO_UPSTREAM: why?
        total_height += step / 2.0

        if port_type == PortType.output:
            x = self._width + self._style.connection_point_diameter
            result = QPointF(x, total_height)
        elif port_type == PortType.input:
            x = -float(self._style.connection_point_diameter)
            result = QPointF(x, total_height)
        else:
            raise ValueError(port_type)

        return t.map(result)
コード例 #23
0
 def paint(self, p=QPainter(), o=QStyleOptionGraphicsItem(), widget=None):
     # p.setRenderHint(QPainter.N)
     p.setPen(self._pen)
     p.setBrush(self._brush)
     p.drawLine(
         QLineF(QPointF(self.b_rect.left(), 0),
                QPointF(self.b_rect.right(), 0)))
     super(HLine, self).paint(p, o, widget)
コード例 #24
0
 def __init__(self, style):
     # local object coordinates
     self._in = QPointF(0, 0)
     self._out = QPointF(0, 0)
     # self._animationPhase = 0
     self._line_width = 3.0
     self._hovered = False
     self._point_diameter = style.connection.point_diameter
コード例 #25
0
ファイル: mapitems.py プロジェクト: bthcode/PyTileMap
    def updatePosition(self, scene):
        pos0 = scene.posFromLonLat(self._lon0, self._lat0)
        pos1 = scene.posFromLonLat(self._lon1, self._lat1)
        deltaPos = QPointF(pos1[0] - pos0[0], pos1[1] - pos0[1])

        self.prepareGeometryChange()
        self.setLine(QLineF(QPointF(0.0, 0.0), deltaPos))
        self.setPos(pos0[0], pos0[1])
コード例 #26
0
    def paintEvent(self, event: QPaintEvent) -> None:
        """Using a QPainter under 'self',
        so just change QPen or QBrush before painting.
        """
        if not self.__grab_mode:
            self.painter.begin(self)
            self.painter.fillRect(event.rect(), QBrush(Qt.white))
        # Translation
        self.painter.translate(self.ox, self.oy)
        # Background
        if not self.background.isNull():
            rect = self.background.rect()
            self.painter.setOpacity(self.background_opacity)
            self.painter.drawImage(
                QRectF(
                    self.background_offset * self.zoom,
                    QSizeF(rect.width(), rect.height()) *
                    self.background_scale * self.zoom), self.background,
                QRectF(rect))
            self.painter.setOpacity(1)
        # Show frame
        pen = QPen(Qt.blue)
        pen.setWidth(1)
        self.painter.setPen(pen)
        self.painter.setFont(QFont("Arial", self.font_size))
        # Draw origin lines
        if self.show_ticks not in {_TickMark.SHOW, _TickMark.SHOW_NUM}:
            return
        pen.setColor(Qt.gray)
        self.painter.setPen(pen)
        x_l = -self.ox
        x_r = self.width() - self.ox
        self.painter.drawLine(QPointF(x_l, 0), QPointF(x_r, 0))
        y_t = self.height() - self.oy
        y_b = -self.oy
        self.painter.drawLine(QPointF(0, y_b), QPointF(0, y_t))

        def indexing(v: float) -> int:
            """Draw tick."""
            return int(v / self.zoom - v / self.zoom % 5)

        # Draw tick
        for x in range(indexing(x_l), indexing(x_r) + 1, 5):
            if x == 0:
                continue
            is_ten = x % 10 == 0
            end = QPointF(x * self.zoom, -10 if is_ten else -5)
            self.painter.drawLine(QPointF(x, 0) * self.zoom, end)
            if self.show_ticks == _TickMark.SHOW_NUM and is_ten:
                self.painter.drawText(end + QPointF(0, 3), f"{x}")
        for y in range(indexing(y_b), indexing(y_t) + 1, 5):
            if y == 0:
                continue
            is_ten = y % 10 == 0
            end = QPointF(10 if is_ten else 5, y * self.zoom)
            self.painter.drawLine(QPointF(0, y) * self.zoom, end)
            if self.show_ticks == _TickMark.SHOW_NUM and is_ten:
                self.painter.drawText(end + QPointF(3, 0), f"{-y}")
コード例 #27
0
 def draw_icon(self, painter):
     path = QPainterPath(QPointF(0, 0))
     path.lineTo(1, 1)
     path.lineTo(0.005, 1)
     path.lineTo(0.5, 0.5)
     path.lineTo(0, 0.9)
     path.closeSubpath()
     painter.drawPath(path)
     painter.drawEllipse(QPointF(0.5, 0.5), 0.05, 0.05)
コード例 #28
0
def round_position(point: QPointF, pixels=5):
    """
    圆整位置。
    :param point:
    :param pixels:圆整的单位(最好是1,2,5,10,20,...)
    :return:
    """
    x, y = point.x(), point.y()
    x_cor, y_cor = round(x * 1.0 / pixels) * pixels, round(y * 1.0 / pixels) * pixels
    return QPointF(x_cor, y_cor)
コード例 #29
0
ファイル: main.py プロジェクト: eyllanesc/QtExamples
def painterPathForTriangle():
    bottomLeft = QPointF(-1.0, -1.0)
    top = QPointF(0.0, 1.0)
    bottomRight = QPointF(1.0, -1.0)

    path = QPainterPath(bottomLeft)
    path.lineTo(top)
    path.lineTo(bottomRight)
    path.closeSubpath()
    return path
コード例 #30
0
    def paint(self, p=QPainter(), o=QStyleOptionGraphicsItem(), widget=None):
        # p.setRenderHint(QPainter.Antialiasing)
        p.setPen(self._pen)
        p.setBrush(self._brush)

        p.drawLine(
            QLineF(QPointF(0, self.b_rect.bottom()),
                   QPointF(0, self.b_rect.top())))

        super(VLine, self).paint(p, o, widget)
コード例 #31
0
ファイル: dag.py プロジェクト: timhowes/git-cola
    def paint(self, painter, option, widget):

        arc_rect = 10
        connector_length = 5

        painter.setPen(self.pen)
        path = QtGui.QPainterPath()

        if self.source.x() == self.dest.x():
            path.moveTo(self.source.x(), self.source.y())
            path.lineTo(self.dest.x(), self.dest.y())
            painter.drawPath(path)

        else:

            # Define points starting from source
            point1 = QPointF(self.source.x(), self.source.y())
            point2 = QPointF(point1.x(), point1.y() - connector_length)
            point3 = QPointF(point2.x() + arc_rect, point2.y() - arc_rect)

            # Define points starting from dest
            point4 = QPointF(self.dest.x(), self.dest.y())
            point5 = QPointF(point4.x(), point3.y() - arc_rect)
            point6 = QPointF(point5.x() - arc_rect, point5.y() + arc_rect)

            start_angle_arc1 = 180
            span_angle_arc1 = 90
            start_angle_arc2 = 90
            span_angle_arc2 = -90

            # If the dest is at the left of the source, then we
            # need to reverse some values
            if self.source.x() > self.dest.x():
                point5 = QPointF(point4.x(), point4.y() + connector_length)
                point6 = QPointF(point5.x() + arc_rect, point5.y() + arc_rect)
                point3 = QPointF(self.source.x() - arc_rect, point6.y())
                point2 = QPointF(self.source.x(), point3.y() + arc_rect)

                span_angle_arc1 = 90

            path.moveTo(point1)
            path.lineTo(point2)
            path.arcTo(QRectF(point2, point3), start_angle_arc1, span_angle_arc1)
            path.lineTo(point6)
            path.arcTo(QRectF(point6, point5), start_angle_arc2, span_angle_arc2)
            path.lineTo(point4)
            painter.drawPath(path)