Ejemplo n.º 1
0
 def addPointMiddle(self, lineIdx, point):
     gripItem = GripItem(self, lineIdx + 1, self.borderColor)
     gripItem.setEnabled(False)
     gripItem.setPos(point)
     self.scene().addItem(gripItem)
     gripItem.updateSize()
     gripItem.setEnabled(True)
     for grip in self.m_items[lineIdx + 1:]:
         grip.m_index += 1
     self.m_items.insert(lineIdx + 1, gripItem)
     self.points.insert(lineIdx + 1, self.mapFromScene(point))
     self.setPolygon(QtGui.QPolygonF(self.points))
     self.bbox.update()
     for line in self.m_lines[lineIdx + 1:]:
         line.idx += 1
     line = QtCore.QLineF(self.mapToScene(self.points[lineIdx]), point)
     self.m_lines[lineIdx].setLine(line)
     lineItem = LineItem(self, lineIdx + 1, self.borderColor)
     line = QtCore.QLineF(
         point,
         self.mapToScene(self.points[(lineIdx + 2) % len(self)]),
     )
     lineItem.setLine(line)
     self.m_lines.insert(lineIdx + 1, lineItem)
     self.scene().addItem(lineItem)
Ejemplo n.º 2
0
    def _levelOfDetailFromTransform(worldTransform):
        if worldTransform.type() <= QtGui.QTransform.TxTranslate:
            return 1  # Translation only? The LOD is 1.

        # Two unit vectors.
        v1 = QtCore.QLineF(0, 0, 1, 0)
        v2 = QtCore.QLineF(0, 0, 0, 1)

        # LOD is the transformed area of a 1x1 rectangle.
        return np.sqrt(worldTransform.map(v1).length() *
                       worldTransform.map(v2).length())
Ejemplo n.º 3
0
 def moveLine(self, i):
     # print("Moving line: ", i, self.noMove)
     if self.noMove:
         return
     points = self.points
     # line[i]
     line = QtCore.QLineF(self.mapToScene(points[i]),
                          self.mapToScene(points[(i + 1) % len(self)]))
     self.m_lines[i].setLine(line)
     # line[i-1]
     line = QtCore.QLineF(self.mapToScene(points[(i - 1) % len(self)]),
                          self.mapToScene(points[i]))
     # print((i - 1) % len(self), len(self.m_lines), len(self))
     self.m_lines[(i - 1) % len(self)].setLine(line)
Ejemplo n.º 4
0
    def drawBackground(self, painter, rect):

        oldTransform = painter.transform()
        painter.fillRect(rect, self._backgroundColor)

        left = int(rect.left()) - (int(rect.left()) % self._gridSizeFine)
        top = int(rect.top()) - (int(rect.top()) % self._gridSizeFine)

        # Draw horizontal fine lines
        gridLines = []
        painter.setPen(self._gridPenS)
        y = float(top)
        while y < float(rect.bottom()):
            gridLines.append(QtCore.QLineF(rect.left(), y, rect.right(), y))
            y += self._gridSizeFine
        painter.drawLines(gridLines)

        # Draw vertical fine lines
        gridLines = []
        painter.setPen(self._gridPenS)
        x = float(left)
        while x < float(rect.right()):
            gridLines.append(QtCore.QLineF(x, rect.top(), x, rect.bottom()))
            x += self._gridSizeFine
        painter.drawLines(gridLines)

        # Draw thick grid
        left = int(rect.left()) - (int(rect.left()) % self._gridSizeCourse)
        top = int(rect.top()) - (int(rect.top()) % self._gridSizeCourse)

        # Draw vertical thick lines
        gridLines = []
        painter.setPen(self._gridPenL)
        x = left
        while x < rect.right():
            gridLines.append(QtCore.QLineF(x, rect.top(), x, rect.bottom()))
            x += self._gridSizeCourse
        painter.drawLines(gridLines)

        # Draw horizontal thick lines
        gridLines = []
        painter.setPen(self._gridPenL)
        y = top
        while y < rect.bottom():
            gridLines.append(QtCore.QLineF(rect.left(), y, rect.right(), y))
            y += self._gridSizeCourse
        painter.drawLines(gridLines)

        return super(GraphView, self).drawBackground(painter, rect)
Ejemplo n.º 5
0
    def sceneEventFilter(self, obj, event):
        if (event.type() == QtCore.QEvent.GraphicsSceneMousePress
                and event.button() == QtCore.Qt.LeftButton):
            assert self.rubberband is None
            self.rubberband = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Line)
            self.rubberband.setGeometry(
                QtCore.QRect(event.screenPos(), QtCore.QSize()))
            self.rubberband.show()
            return True

        if (event.type() == QtCore.QEvent.GraphicsSceneMouseRelease
                and event.button() == QtCore.Qt.LeftButton):
            assert self.rubberband is not None
            self.rubberband.hide()
            self.rubberband = None
            line = QtCore.QLineF(
                event.buttonDownScenePos(QtCore.Qt.LeftButton),
                event.scenePos())
            item = obj.addLine(line, self.pen)
            item.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
            item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
            return True

        elif (event.type() == QtCore.QEvent.GraphicsSceneMouseMove
              and bool(event.buttons() & QtCore.Qt.LeftButton)):
            assert self.rubberband is not None
            rect = QtCore.QRect(
                event.buttonDownScreenPos(QtCore.Qt.LeftButton),
                event.screenPos()).normalized()
            self.rubberband.setGeometry(rect)
            return True

        return False
Ejemplo n.º 6
0
    def removeFocusPoint(self):
        focusIdx = None
        for idx, item in enumerate(self.m_items):
            if item.hasFocus():
                focusIdx = idx
                break
        if focusIdx is not None:
            if len(self) <= 3:
                self.delPolygon(self)  # 调用app的删除多边形,为了同时删除coco标签
                return
            del self.points[focusIdx]
            self.setPolygon(QtGui.QPolygonF(self.points))
            self.bbox.update()
            self.scene().removeItem(self.m_items[focusIdx])
            del self.m_items[focusIdx]
            for grip in self.m_items[focusIdx:]:
                grip.m_index -= 1

            self.scene().removeItem(self.m_lines[focusIdx])
            del self.m_lines[focusIdx]
            line = QtCore.QLineF(
                self.mapToScene(self.points[(focusIdx - 1) % len(self)]),
                self.mapToScene(self.points[focusIdx % len(self)]),
            )
            # print((focusIdx - 1) % len(self), len(self.m_lines), len(self))
            self.m_lines[(focusIdx - 1) % len(self)].setLine(line)
            for line in self.m_lines[focusIdx:]:
                line.idx -= 1
Ejemplo n.º 7
0
    def plotHorizon(self):

        if self.cbShowHorizon.isChecked():
            # delete old horizon
            self.deleteHorizon()

            # get coordinates
            p1 = self.camera.getImageHorizon()[0]
            p2 = self.camera.getImageHorizon()[-1]
            print(p1, p2)

            # set pen
            pen = QtGui.QPen(QtGui.QColor("#00ffff"))
            pen.setWidth(5)
            pen.setCosmetic(True)

            # add object
            self.horizon_line = QtWidgets.QGraphicsLineItem(
                QtCore.QLineF(QtCore.QPointF(*p1), QtCore.QPointF(*p2)))
            self.horizon_line.setPen(pen)
            self.horizon_line.setParentItem(self.cp.window.view.origin)
            self.horizon_line.setZValue(100)

        else:
            self.deleteHorizon()
Ejemplo n.º 8
0
    def __init__(self, source, dest):

        QtWidgets.QGraphicsItem.__init__(self)

        self.setAcceptedMouseButtons(Qt.NoButton)
        self.source = source
        self.dest = dest
        self.commit = source.commit
        self.setZValue(-2)

        dest_pt = Commit.item_bbox.center()

        self.source_pt = self.mapFromItem(self.source, dest_pt)
        self.dest_pt = self.mapFromItem(self.dest, dest_pt)
        self.line = QtCore.QLineF(self.source_pt, self.dest_pt)

        width = self.dest_pt.x() - self.source_pt.x()
        height = self.dest_pt.y() - self.source_pt.y()
        rect = QtCore.QRectF(self.source_pt, QtCore.QSizeF(width, height))
        self.bound = rect.normalized()

        # Choose a new color for new branch edges
        if self.source.x() < self.dest.x():
            color = EdgeColor.cycle()
            line = Qt.SolidLine
        elif self.source.x() != self.dest.x():
            color = EdgeColor.current()
            line = Qt.SolidLine
        else:
            color = EdgeColor.current()
            line = Qt.SolidLine

        self.pen = QtGui.QPen(color, 4.0, line, Qt.SquareCap, Qt.RoundJoin)
Ejemplo n.º 9
0
    def updatePolygon(self, marker):
        self.cp.save()
        # print("Update Polygon")
        marker = self.db.getMarkers(type=marker.type, image=marker.image)
        # print("%d marker found" % marker.count())

        if not marker[0].type.name in self.lines.keys():
            self.lines[marker[0].type.name] = []

        ## draw element
        # cleanup current line
        try:
            _ = [
                line.scene().removeItem(line)
                for line in self.lines[marker[0].type.name]
            ]
            self.lines[marker[0].type.name] = []
        except:
            pass

        # set pen
        pen = QtGui.QPen(QtGui.QColor(marker[0].type.color))
        pen.setWidth(2)
        pen.setCosmetic(True)

        # draw vertices
        for i in np.arange(0, marker.count() - 1):
            # add object
            line = QtWidgets.QGraphicsLineItem(
                QtCore.QLineF(QtCore.QPointF(*marker[i].pos()),
                              QtCore.QPointF(*marker[i + 1].pos())))

            self.lines[marker[0].type.name].append(line)

        # draw closing vertices
        line = QtWidgets.QGraphicsLineItem(
            QtCore.QLineF(QtCore.QPointF(*marker[marker.count() - 1].pos()),
                          QtCore.QPointF(*marker[0].pos())))
        self.lines[marker[0].type.name].append(line)

        # set Pen, ZValue, and Display Parent
        _ = [line.setPen(pen) for line in self.lines[marker[0].type.name]]
        _ = [line.setZValue(100) for line in self.lines[marker[0].type.name]]
        _ = [
            line.setParentItem(self.cp.window.view.origin)
            for line in self.lines[marker[0].type.name]
        ]
Ejemplo n.º 10
0
    def joystickDirection(self):
        if not self.grabCenter:
            return (0, 0)
        normVector = QtCore.QLineF(self._center(), self.movingOffset)
        currentDistance = normVector.length()
        angle = normVector.angle()

        distance = min(currentDistance / self.__maxDistance, 1.0)

        return (angle, distance)
Ejemplo n.º 11
0
    def addPointLast(self, p):
        grip = GripItem(self, len(self), self.borderColor)
        self.scene().addItem(grip)
        self.m_items.append(grip)
        grip.updateSize()
        grip.setPos(p)
        if len(self) == 0:
            line = LineItem(self, len(self), self.borderColor)
            self.scene().addItem(line)
            self.m_lines.append(line)
            line.setLine(QtCore.QLineF(p, p))
        else:
            self.m_lines[-1].setLine(QtCore.QLineF(self.points[-1], p))
            line = LineItem(self, len(self), self.borderColor)
            self.scene().addItem(line)
            self.m_lines.append(line)
            line.setLine(QtCore.QLineF(p, self.points[0]))

        self.points.append(p)
        self.setPolygon(QtGui.QPolygonF(self.points))
        self.bbox.update()
Ejemplo n.º 12
0
    def _intersectionPointsAndAngles(r, ratioEllispeRectangle):
        '''
        return all 8  x and y coords of lines build by intersection of ellipse and rect
        '''
        w = r.width()
        h = r.height()
        x1 = 0.5 * w
        y2 = 0.5 * h

        # ellipse parameters:
        a = x1 * ratioEllispeRectangle
        b = y2 * ratioEllispeRectangle
        # intersection coords in the 1st quadrant with center=(0,0):
        y1 = ((1 - (x1**2 / a**2)) * b**2)**0.5
        x2 = ((1 - (y2**2 / b**2)) * a**2)**0.5

        c = r.center()
        cx = c.x()
        cy = c.y()

        # edge points:
        p1 = QtCore.QPointF(cx + x1, cy + y1)
        p2 = QtCore.QPointF(cx + x2, cy + y2)
        p3 = QtCore.QPointF(cx - x2, cy + y2)
        p4 = QtCore.QPointF(cx - x1, cy + y1)
        p5 = QtCore.QPointF(cx - x1, cy - y1)
        p6 = QtCore.QPointF(cx - x2, cy - y2)
        p7 = QtCore.QPointF(cx + x2, cy - y2)
        p8 = QtCore.QPointF(cx + x1, cy - y1)

        # angle in as degree*16 (needed in .drawArc)
        a1 = int(QtCore.QLineF(c, p1).angle() * 16)
        a2 = int(QtCore.QLineF(c, p2).angle() * 16)
        a4 = int(QtCore.QLineF(c, p4).angle() * 16)
        a6 = int(QtCore.QLineF(c, p6).angle() * 16)
        a8 = int(QtCore.QLineF(c, p8).angle() * 16)

        arc_length = a1 - a2
        return (p1, p2, p3, p4, p5, p6, p7, p8), (a2, a4, a6, a8), arc_length
Ejemplo n.º 13
0
    def __init__(self, parent, color, base_pt, camera, scalebox_dim):
        # get the base position in the plane
        base_pos = camera.spaceFromImage(base_pt, Z=0).T
        print("### base", base_pos, base_pt)

        # get the top position
        top_pos = base_pos + np.array([0, 0, scalebox_dim])
        top_pt = camera.imageFromSpace(top_pos)
        print("### top", top_pos, top_pt)

        # get the left position
        left_pos = base_pos + np.array([scalebox_dim, 0, 0])
        left_pt = camera.imageFromSpace(left_pos)
        print("### left", left_pos, left_pt)

        # get the back position
        back_pos = base_pos + np.array([0, scalebox_dim, 0])
        back_pt = camera.imageFromSpace(back_pos)
        print("### back", back_pos, back_pt)

        ## draw element
        # set pen
        pen = QtGui.QPen(QtGui.QColor("#ff5f00"))
        pen.setWidth(5)
        pen.setCosmetic(True)

        # add object
        line_top = QtWidgets.QGraphicsLineItem(
            QtCore.QLineF(QtCore.QPointF(*base_pt), QtCore.QPointF(*top_pt)))
        line_left = QtWidgets.QGraphicsLineItem(
            QtCore.QLineF(QtCore.QPointF(*base_pt), QtCore.QPointF(*left_pt)))
        line_back = QtWidgets.QGraphicsLineItem(
            QtCore.QLineF(QtCore.QPointF(*base_pt), QtCore.QPointF(*back_pt)))

        self.lines = [line_top, line_left, line_back]

        _ = [line.setPen(pen) for line in self.lines]
        _ = [line.setParentItem(parent) for line in self.lines]
        _ = [line.setZValue(100) for line in self.lines]
Ejemplo n.º 14
0
 def drawArrows(self, path, i):
     d = self.point_size / self.scale
     shape = self.point_type
     point = self.points[i]
     if i == self._highlightIndex:
         size, shape = self._highlightSettings[self._highlightMode]
         d *= size
     if self._highlightIndex is not None:
         self.vertex_fill_color = self.hvertex_fill_color
     else:
         self.vertex_fill_color = Shape.vertex_fill_color
     line = QtCore.QLineF(self.points[i-1], self.points[i])
     nv = line.normalVector()
     nv.setLength(5)
     pv = line.unitVector()
     pv.setLength(30)
     p = line.p2() - QtCore.QPointF(pv.dx(), pv.dy())
     x1, x2 = (p + i*QtCore.QPointF(nv.dx(), nv.dy()) for i in (1, -1))
     path.moveTo(x1)
     path.lineTo(line.p2())
     path.lineTo(x2)
Ejemplo n.º 15
0
def singleGeometryToGraphicsItem(geom, transform=None):
    """Convert a single OGR geometry into a Qt5 graphics item.

    A "single geometry" is an OGR geometry that don't include other
    geometries (GetGeometryCount() == 0).

    If the *transform* callable is provided then each point in the
    geometry is converted using the `transform(x, y, z)` call before
    generating the graphics item path.

    .. note: for 2.5D geometries the *z* value is ignored.

    :param geom:
        a single OGR geometry
    :param transform:
        callable object for arbitrary coordinate conversion
    :returns:
        a Qt5 graphics item representing the geometry

    .. seealso:: :func:`geometryToGraphicsItem`

    """

    assert geom.GetGeometryCount() == 0

    gtype = geom.GetGeometryType()
    if gtype in (ogr.wkbPoint, ogr.wkbPoint25D):

        # @TODO: check
        RADIUS = 3

        point = geom.GetPoint()
        if transform:
            point = transform(*point)
        qitem = qtdraw.GraphicsPointItem(point[0], point[1], RADIUS)

        # @TODO: style options should be set in a more general way.
        #        Probably it is better to set them in an external function.
        # Red point
        pen = qitem.pen()
        pen.setColor(QtCore.Qt.red)
        # pen.setWidth(15)
        qitem.setPen(pen)

        brush = qitem.brush()
        brush.setColor(QtCore.Qt.red)
        # brush.setStyle(QtCore.Qt.SolidPattern)
        qitem.setBrush(brush)

    elif (gtype in (ogr.wkbLineString, ogr.wkbLineString25D)
          and geom.GetPointCount() == 2):
        p0 = geom.GetPoint(0)
        p1 = geom.GetPoint(1)
        if transform:
            p0 = transform(*p0)
            p1 = transform(*p1)
        qline = QtCore.QLineF(p0[0], p0[1], p1[0], p1[1])
        qitem = QtWidgets.QGraphicsLineItem(qline)

    elif gtype in (ogr.wkbLinearRing, ogr.wkbPolygon, ogr.wkbPolygon25D,
                   ogr.wkbLineString, ogr.wkbLineString25D):

        # @NOTE: use only if geometry is a ring
        if geom.IsRing():
            qpoly = QtGui.QPolygonF(geom.GetPointCount())
            for index in range(geom.GetPointCount()):
                point = geom.GetPoint(index)
                if transform:
                    point = transform(*point)
                qpoly[index] = QtCore.QPointF(point[0], point[1])
            qitem = QtWidgets.QGraphicsPolygonItem(qpoly)
            # qitem.setFillRule(QtCore.Qt.WindingFill)    # @TODO: check
        else:
            qpath = QtGui.QPainterPath()
            # qpath.setFillRule(QtCore.Qt.WindingFill)    # @TODO: check
            point = geom.GetPoint(0)
            if transform:
                point = transform(*point)
            qpath.moveTo(point[0], point[1])
            for index in range(1, geom.GetPointCount()):
                point = geom.GetPoint(index)
                if transform:
                    point = transform(*point)
                qpath.lineTo(point[0], point[1])
            qitem = QtWidgets.QGraphicsPathItem(qpath)

    elif gtype in (ogr.wkbMultiPoint, ogr.wkbMultiPoint25D,
                   ogr.wkbMultiLineString, ogr.wkbMultiLineString25D,
                   ogr.wkbMultiPolygon, ogr.wkbMultiPolygon25D,
                   ogr.wkbGeometryCollection, ogr.wkbGeometryCollection25D):

        raise ValueError('should not happen.')

    elif gtype in (ogr.wkbUnknown, ogr.wkbNone):
        raise ValueError('invalid geometry type: '
                         '"%s"' % geom.GetGeometryName())

    else:
        raise ValueError('invalid geometry type: "%d"' % gtype)

    return qitem
Ejemplo n.º 16
0
def connect_widgets(scene, parent, visited=[]):
    if parent in visited:
        return
    visited.append(parent)

    pen = QtGui.QPen(QtGui.QColor("deepskyblue"), 3)
    pen.setCapStyle(QtCore.Qt.FlatCap)
    pen.setJoinStyle(QtCore.Qt.RoundJoin)

    connections = dict()
    for node in parent.walk_depth_first():
        try:
            dir = parent.get_direction_to_child(node)
        except ValueError:
            continue
        child = list(node.walk_depth_first())
        if len(child) > 1:
            connect_widgets(scene, node, visited=visited)
        connections[dir] = node

    for dir, node in connections.items():
        p_w = parent.widget.width()
        p_h = parent.widget.height()

        n_w = node.widget.width()
        n_h = node.widget.height()

        l_x1 = parent.shape.pos().x()
        l_y1 = parent.shape.pos().y()
        l_x2 = node.shape.pos().x()
        l_y2 = node.shape.pos().y()

        if dir == 'n':
            l_x1 += p_w / 2.0
            l_y1 += 0.0
            l_x2 += n_w / 2.0
            l_y2 += n_h
        elif dir == 's':
            l_x1 += p_w / 2.0
            l_y1 += p_h
            l_x2 += n_w / 2.0
            l_y2 += 0.0
        elif dir == 'e':
            l_x1 += p_w
            l_y1 += p_h / 2.0
            l_x2 += 0.0
            l_y2 += n_h / 2.0
        elif dir == 'w':
            l_x1 += 0.0
            l_y1 += p_h / 2.0
            l_x2 += n_w
            l_y2 += n_h / 2.0
        elif dir == 'nw':
            l_x1 += 0
            l_y1 += 0
            l_x2 += n_w
            l_y2 += n_h
        elif dir == 'ne':
            l_x1 += p_w
            l_y1 += 0
            l_x2 += 0
            l_y2 += n_h
        elif dir == 'sw':
            l_x1 += 0
            l_y1 += p_h
            l_x2 += n_w
            l_y2 += 0
        elif dir == 'se':
            l_x1 += p_w
            l_y1 += p_h
            l_x2 += 0
            l_y2 += 0

        scene.addLine(QtCore.QLineF(l_x1, l_y1, l_x2, l_y2), pen)
Ejemplo n.º 17
0
 def ptDist(self, pt1, pt2):
     # A line between both
     line = QtCore.QLineF(pt1, pt2)
     # Length
     lineLength = line.length()
     return lineLength
Ejemplo n.º 18
0
 def _boundJoystick(self, point):
     limitLine = QtCore.QLineF(self._center(), point)
     if (limitLine.length() > self.__maxDistance):
         limitLine.setLength(self.__maxDistance)
     return limitLine.p2()
Ejemplo n.º 19
0
    def mouseMoveEvent(self, ev):
        """Update line with last point and current coordinates."""
        try:
            if QT5:
                pos = self.transformPos(ev.localPos())
            else:
                pos = self.transformPos(ev.posF())
        except AttributeError:
            return

        self.prevMovePoint = pos
        self.restoreCursor()

        # Polygon drawing.
        if self.drawing():
            self.line.shape_type = self.createMode

            self.overrideCursor(CURSOR_DRAW)
            if not self.current:
                return

            if self.outOfPixmap(pos):
                # Don't allow the user to draw outside the pixmap.
                # Project the point to the pixmap's edges.
                pos = self.intersectionPoint(self.current[-1], pos)
            elif (
                len(self.current) > 1
                and self.createMode == "polygon"
                and self.closeEnough(pos, self.current[0])
            ):
                # Attract line to starting point and
                # colorise to alert the user.
                pos = self.current[0]
                self.overrideCursor(CURSOR_POINT)
                self.current.highlightVertex(0, Shape.NEAR_VERTEX)
            if self.createMode in ["polygon", "linestrip", "trace"]:
                self.line[0] = self.current[-1]
                self.line[1] = pos
            if self.createMode == "trace":
                length = QtCore.QLineF(self.line[1], self.line[0]).length()
                if length > 1 and not self.pause_tracing:
                    self.current.addPoint(self.line[1])
                    self.line[0] = self.current[-1]
            elif self.createMode == "rectangle":
                self.line.points = [self.current[0], pos]
                self.line.close()
            elif self.createMode == "circle":
                self.line.points = [self.current[0], pos]
                self.line.shape_type = "circle"
            elif self.createMode == "line":
                self.line.points = [self.current[0], pos]
                self.line.close()
            elif self.createMode == "point":
                self.line.points = [self.current[0]]
                self.line.close()
            self.repaint()
            self.current.highlightClear()
            return

        # Polygon copy moving.
        if QtCore.Qt.RightButton & ev.buttons():
            if self.selectedShapesCopy and self.prevPoint:
                self.overrideCursor(CURSOR_MOVE)
                self.boundedMoveShapes(self.selectedShapesCopy, pos)
                self.repaint()
            elif self.selectedShapes:
                self.selectedShapesCopy = [
                    s.copy() for s in self.selectedShapes
                ]
                self.repaint()
            return

        # Polygon/Vertex moving.
        if QtCore.Qt.LeftButton & ev.buttons():
            if self.selectedVertex():
                self.boundedMoveVertex(pos)
                self.repaint()
                self.movingShape = True
            elif self.selectedShapes and self.prevPoint:
                self.overrideCursor(CURSOR_MOVE)
                self.boundedMoveShapes(self.selectedShapes, pos)
                self.repaint()
                self.movingShape = True
            return

        # Just hovering over the canvas, 2 possibilities:
        # - Highlight shapes
        # - Highlight vertex
        # Update shape/vertex fill and tooltip value accordingly.
        self.setToolTip(self.tr("Image"))
        for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
            # Look for a nearby vertex to highlight. If that fails,
            # check if we happen to be inside a shape.
            index = shape.nearestVertex(pos, self.epsilon / self.scale)
            index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
            if index is not None:
                if self.selectedVertex():
                    self.hShape.highlightClear()
                self.prevhVertex = self.hVertex = index
                self.prevhShape = self.hShape = shape
                self.prevhEdge = self.hEdge = index_edge
                shape.highlightVertex(index, shape.MOVE_VERTEX)
                self.overrideCursor(CURSOR_POINT)
                self.setToolTip(self.tr("Click & drag to move point"))
                self.setStatusTip(self.toolTip())
                self.update()
                break
            elif shape.containsPoint(pos):
                if self.selectedVertex():
                    self.hShape.highlightClear()
                self.prevhVertex = self.hVertex
                self.hVertex = None
                self.prevhShape = self.hShape = shape
                self.prevhEdge = self.hEdge = index_edge
                self.setToolTip(
                    self.tr("Click & drag to move shape '%s'") % shape.label
                )
                self.setStatusTip(self.toolTip())
                self.overrideCursor(CURSOR_GRAB)
                self.update()
                break
        else:  # Nothing found, clear highlights, reset state.
            self.unHighlight()
        self.edgeSelected.emit(self.hEdge is not None, self.hShape)
        self.vertexSelected.emit(self.hVertex is not None)
Ejemplo n.º 20
0
     "QLineEdit": QtWidgets.QLineEdit("coucou"),
     "QPlainTextEdit": QtWidgets.QPlainTextEdit("coucou"),
     "QSpinBox": QtWidgets.QSpinBox(value=20),
     "QPushButton": QtWidgets.QPushButton(),
 },
 "PyQt_pickable": {
     "QByteArray": QtCore.QByteArray(bytes(range(256))),
     "QColor": QtGui.QColor(10, 20, 30, 40),
     ## "QChar": # n'a plus l'air d'exister dans PyQt5
     "QDate": QtCore.QDate(2020, 10, 31),
     "QDateTime": QtCore.QDateTime(2020, 10, 31, 20, 30),
     "QKeySequence": QtGui.QKeySequence(),
     ## "QLatin1Char": # n'a plus l'air d'exister dans PyQt5
     ## "QLatin1String"# n'a plus l'air d'exister dans PyQt5
     "QLine": QtCore.QLine(QtCore.QPoint(0, 1), QtCore.QPoint(2, 3)),
     "QLineF": QtCore.QLineF(QtCore.QPoint(0.0, 1.1), QtCore.QPoint(2.2, 3.3)),
     "QPen": QtGui.QPen(),
     "QBrush": QtGui.QBrush(),
     "QPoint": QtCore.QPoint(0, 1),
     "QPointF": QtCore.QPointF(0.0, 1.1),
     "QPolygon": QtGui.QPolygon([QtCore.QPoint(0, 1), QtCore.QPoint(2, 3)]),
     "QPolygonF": QtGui.QPolygonF([QtCore.QPoint(0.0, 1.1), QtCore.QPoint(2.2, 3.3)]),
     "QRect": QtCore.QRect(QtCore.QPoint(0, 1), QtCore.QPoint(2, 3)),
     "QRectF": QtCore.QRectF(QtCore.QPoint(0.0, 1.1), QtCore.QPoint(2.2, 3.3)),
     "QSize": QtCore.QSize(10, 20),
     "QSizeF": QtCore.QSizeF(10.5, 20.5),
     ## "QMatrix": # Support for the deprecated QMatrix class has been removed
     ## "QString": # n'a plus l'air d'exister dans PyQt5
     "QTime": QtCore.QTime(20, 30),
     "QTransform": QtGui.QTransform(),  # pas reducable dans documentation ?
     "QVector3D": QtGui.QVector3D(),  # pas reducable dans documentation ?