Example #1
0
 def draw_line(self, start, end, EnablePlot=True):
     self.clear_canvas()
     if QtGui.QGuiApplication.queryKeyboardModifiers().__eq__(
             QtCore.Qt.ShiftModifier):
         if end.x() == start.x():
             slope = 10
         else:
             slope = (end.y() - start.y()) / (end.x() - start.x())
         if slope > np.tan(np.pi / 3):
             end.setX(start.x())
         elif slope < np.tan(np.pi / 6):
             end.setY(start.y())
         else:
             end.setY(end.x() - start.x() + start.y())
     self._lineItem = self._scene.addLine(QtCore.QLineF(start, end),
                                          QtGui.QPen(QtCore.Qt.yellow, 1))
     self._lineItem.show()
     self.canvasObject = "line"
     self.saveStart, self.saveEnd = start, end
     if EnablePlot:
         self.PLOT_LINE_SCAN.emit(start, end)
Example #2
0
        def draw_x_ticks(self, painter):
            w, h = self.wh
            xmin, xmax, xinc = self.xscaler.make_scale(
                (self._xmin, self._xmax))
            _xinc = self._xinc or xinc
            if self.xticks:
                ticks = num.arange(xmin, xmax, _xinc)
                ticks_proj = self.xproj(ticks)
                tick_anchor = (1. - self.top) * h
                lines = [
                    qc.QLineF(xval, tick_anchor * 0.8, xval, tick_anchor)
                    for xval in ticks_proj
                ]

                painter.drawLines(lines)
                if self.xlabels:
                    formatter = self.xtick_formatter
                    for i, xval in enumerate(ticks):
                        painter.drawText(
                            qc.QPointF(ticks_proj[i], tick_anchor * 0.75),
                            formatter % xval)
Example #3
0
        def draw_y_ticks(self, painter):
            w, h = self.wh
            ymin, ymax, yinc = self.yscaler.make_scale(
                (self._ymin, self._ymax))
            if self.scroll_increment == 0:
                self.scroll_increment = yinc / 4

            _yinc = self._yinc or yinc
            ticks = num.arange(ymin, ymax, _yinc)
            ticks_proj = self.yproj(ticks)
            if self.yticks:
                lines = [
                    qc.QLineF(w * self.left * 0.8, yval, w * self.left, yval)
                    for yval in ticks_proj
                ]
                painter.drawLines(lines)
                if self.ylabels:
                    for i, yval in enumerate(ticks):
                        formatter = self.ytick_formatter or '%s'
                        painter.drawText(qc.QPointF(0, ticks_proj[i]),
                                         formatter % (yval))
Example #4
0
 def calibrate(self, scaleFactor, scaleBarLength, fontname, fontsize):
     if self.has_photo():
         self.photorect = self._photo.boundingRect()
         self._scaleBarText.setPlainText(
             "{} \u212B\u207B\u00B9".format(scaleBarLength))
         self._scaleBarText.setFont(QtGui.QFont(fontname, fontsize))
         self._scaleBarText.setPos(180, self.photorect.height() - 200)
         self._scaleBarText.show()
         self.scaleBarLength = scaleBarLength * scaleFactor
         x1,y1,x2,y2 =180+self._scaleBarText.boundingRect().width()/2-self.scaleBarLength/2,\
                      self.photorect.height()-160+fontsize*4/3,\
                      180+self._scaleBarText.boundingRect().width()/2+self.scaleBarLength/2,\
                      self.photorect.height()-160+fontsize*4/3
         if x1 < 30:
             self._scaleBarText.setPos(180 + 30 - x1,
                                       self.photorect.height() - 200)
             x2 += 30 - x1
             x1 = 30
         self._scaleBarLine.setLine(QtCore.QLineF(x1, y1, x2, y2))
         self._scaleBarLine.show()
         self._scaleBarIsPresent = True
Example #5
0
    def updateLine(self, value):
            
        self.scene.clear()

        pen = QtGui.QPen(QtCore.Qt.red, 5, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap)

        x1 = self.graphicsView.width()/2
        y1 = self.graphicsView.height()/2

        line_length = self.graphicsView.width()/2 - 10
        angle = (math.radians(ANGLE_RANGE) * value)/MAX_RPM_VALUE
        angle_offset = (360 - ANGLE_RANGE)/2
        x2 = line_length * math.sin(angle + math.radians(angle_offset))
        y2 = -1 * line_length * math.cos(angle + math.radians(angle_offset))

        #print line_length, '|', value, '|', math.degrees(angle), '|', x2, y2
        
        line = QtCore.QLineF(x1, y1 ,x1-x2,y1-y2)
        lineItem = QtWidgets.QGraphicsLineItem(line)
        self.scene.addItem(lineItem)
        lineItem.setPen(pen)
Example #6
0
    def breakPointAdd(self, mousePos):
        """
        Create a new breakpoint from the given mouse position returning its index.
        :type mousePos: QtCore.QPointF
        :rtype: int
        """
        index = 0
        point = None
        between = None
        shortest = 999

        source = self.source.anchor(self)
        target = self.target.anchor(self)
        points = [source] + self.breakpoints + [target]

        # Estimate between which breakpoints the new one is being added.
        for subpath in (QtCore.QLineF(points[i], points[i + 1]) for i in range(len(points) - 1)):
            dis, pos = projection(subpath, mousePos)
            if dis < shortest:
                point = pos
                shortest = dis
                between = subpath.p1(), subpath.p2()

        # If there is no breakpoint the new one will be appended.
        for i, breakpoint in enumerate(self.breakpoints):

            if breakpoint == between[1]:
                # In case the new breakpoint is being added between
                # the source node of this edge and the last breakpoint.
                index = i
                break

            if breakpoint == between[0]:
                # In case the new breakpoint is being added between
                # the last breakpoint and the target node of this edge.
                index = i + 1
                break

        self.session.undostack.push(CommandEdgeBreakpointAdd(self.diagram, self, index, point))
        return index
Example #7
0
 def test_intersection(self):
     self.assertEqual(
         QtCore.QPointF(0, 0),
         intersection(
             QtCore.QLineF(QtCore.QPointF(-1, 0), QtCore.QPointF(1, 0)),
             QtCore.QLineF(QtCore.QPointF(0, -1), QtCore.QPointF(0, 1))))
     self.assertEqual(
         QtCore.QPointF(-4, 0),
         intersection(
             QtCore.QLineF(QtCore.QPointF(-10, 0), QtCore.QPointF(10, 0)),
             QtCore.QLineF(QtCore.QPointF(-4, -12), QtCore.QPointF(-4,
                                                                   14))))
     self.assertIsNone(
         intersection(
             QtCore.QLineF(QtCore.QPointF(-1, 0), QtCore.QPointF(1, 0)),
             QtCore.QLineF(QtCore.QPointF(-1, 2), QtCore.QPointF(1, 2))))
Example #8
0
def updateThrust(gui):
    """ Update the thrust direction plot """

    xy = np.array(
        [gui.State['z0'] - gui.State['z2'], gui.State['z1'] - gui.State['z3']])

    if norm(xy) > 77:
        xy = 77 * xy / norm(xy)

    centerx = gui.xyfbg.x() + gui.xyfbg.width() / 2
    centery = gui.xyfbg.y() + gui.xyfbg.height() / 2
    center = QtCore.QPointF(centerx, centery)

    xy = QtCore.QPointF(centerx + xy[0], centery + xy[1])
    line = QtCore.QLineF(center, xy)
    pen = QtGui.QPen(QtGui.QColor(colors.active_blue))
    pen.setWidthF(3)

    if hasattr(gui, 'xyflineref'):
        gui.xyflineref.setLine(line)
    else:
        gui.xyflineref = gui.scene.addLine(line, pen)
Example #9
0
    def getLines(self, obj):
        lines = []
        for line in obj.lines:
            if obj.vertices_depth[line[0]]<0 and obj.vertices_depth[line[1]]<0:
                continue
            elif obj.vertices_depth[line[0]]<0 or obj.vertices_depth[line[1]]<0:
                if self.currentFile:
                    frame = int(os.path.splitext(os.path.basename( self.currentFile ))[0])
                    v = [obj.vertices[line[0]]*x + obj.vertices[line[1]]*(1-x) for x in np.arange(0,1,0.1)]
                    uv, d = self.camera.project_vertices(np.asarray(v), frame)
                    d[d<0] = 1e+6
                    vidx = line[0] if obj.vertices_depth[line[0]] < 0 else line[1]
                    obj.vertices_proj[0][vidx] = uv[0][np.argmin(d)]
                    obj.vertices_proj[1][vidx] = uv[1][np.argmin(d)]
                else:
                    continue

            lines.append( QtCore.QLineF(obj.vertices_proj[0][line[0]],
                                  obj.vertices_proj[1][line[0]],
                                  obj.vertices_proj[0][line[1]],
                                  obj.vertices_proj[1][line[1]] ) )
        return lines
Example #10
0
    def ulkoinen_voima_nuoli_alatuki(self):
        '''Nuolen kärkien koordinaatit alhaalta tuetulle palkille'''
        nuoli_piste_1 = QtCore.QPointF(self.palkin_keskipiste - 7, 185)
        nuoli_piste_2 = QtCore.QPointF(self.palkin_keskipiste, 200)
        nuoli_piste_3 = QtCore.QPointF(self.palkin_keskipiste + 7, 185)
        viiva_x = self.palkin_keskipiste
        '''Luodaan nuoli QPolygonItem olio'''
        self.nuoli_6 = QGraphicsPolygonItem(
            QtGui.QPolygonF([nuoli_piste_1, nuoli_piste_2, nuoli_piste_3]))
        self.nuoli_brush = QtGui.QBrush(1)
        self.nuoli_pencil = QtGui.QPen(QtCore.Qt.black, 2)
        self.nuoli_pencil.setStyle(QtCore.Qt.SolidLine)

        self.viiva_5 = QGraphicsLineItem(
            QtCore.QLineF(viiva_x, 100, viiva_x, 200))
        '''Lisätään viiva sekä päiden nuolet sceneen'''
        self.scene.addItem(self.viiva_5)
        self.scene.addItem(self.nuoli_6)
        self.viiva_5.hide()
        self.nuoli_6.hide()
        '''Lisätään tieto, että voima on asetettu'''
        Ominaisuudet.ulkoinen_voima(self, 1)
Example #11
0
    def __init__(self, parent, config):
        super(Canvas, self).__init__(parent)
        self._mode = "pan"
        self.canvasObject = "none"
        self._drawingLine = False
        self._drawingRect = False
        self._drawingArc = False
        self._mouseIsPressed = False
        self._mouseIsMoved = False
        self._zoom = 0
        self._scaleFactor = 1
        self._empty = True

        #Defaults
        canvasDefault = dict(config['canvasDefault'].items())
        self.widthInAngstrom = float(canvasDefault['widthinangstrom'])
        self.radiusMaximum = int(canvasDefault['radiusmaximum'])
        self.span = int(canvasDefault['span'])
        self.tilt = int(canvasDefault['tilt'])
        self.max_zoom_factor = int(canvasDefault['max_zoom_factor'])

        self._scene = QtWidgets.QGraphicsScene(self)
        self._photo = QtWidgets.QGraphicsPixmapItem()
        self._scene.addItem(self._photo)
        self._labelText = self._scene.addText("")
        self._labelText.setDefaultTextColor(QtGui.QColor("white"))
        self._scaleBarText = self._scene.addText("")
        self._scaleBarText.setDefaultTextColor(QtGui.QColor("white"))
        self._scaleBarLine = self._scene.addLine(
            QtCore.QLineF(1, 2, 1, 2), QtGui.QPen(QtCore.Qt.white, 10))
        self._scaleBarLine.hide()
        self.setScene(self._scene)

        self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor('darkGray')))
        self.setFrameShape(QtWidgets.QFrame.NoFrame)
Example #12
0
 def filter_measurement_by_distance_to_line(
     self,
     unassociated_lidar_measurements,
     line,
         distance):
     filtered_measures = {}
     normal_line = line.normalVector()
     for index, dot in unassociated_lidar_measurements.items():
         intersect_dot = geometry.intersect_by_secant(
             QtCore.QPointF(
                 dot[0], dot[1]),
             normal_line,
             (line,),
             check_line_contain_point=False)
         if len(intersect_dot) != 1:
             LOG.critical(
                 "RANSAC: ERROR in filter_measurement_by_distance_to_line")
         if (QtCore.QLineF(
                 intersect_dot[0], QtCore.QPointF(
                     dot[0],
                     dot[1])).length() <= distance):
             filtered_measures[index] = dot
     return filtered_measures
Example #13
0
    def anchorMove(self, node, mousePos):
        """
        Move the selected anchor point.
        :type node: AbstractNode
        :type mousePos: QtCore.QPointF
        """
        nodePos = node.pos()
        snapToGrid = self.session.action('toggle_grid').isChecked()
        mousePos = snap(mousePos, self.diagram.GridSize, snapToGrid)
        path = self.mapFromItem(node, node.painterPath())
        if path.contains(mousePos):
            # Mouse is inside the shape => use this position as anchor point.
            pos = nodePos if distance(mousePos, nodePos) < 10.0 else mousePos
        else:
            # Mouse is outside the shape => use the intersection point as anchor point.
            pos = node.intersection(QtCore.QLineF(mousePos, nodePos))
            for pair in set(permutations([-1, -1, 0, 0, 1, 1], 2)):
                p = pos + QtCore.QPointF(*pair)
                if path.contains(p):
                    pos = p
                    break

        node.setAnchor(self, pos)
Example #14
0
    def mouseMoveEvent(self, event):
        """If the mouse is pressed and has moved far enough, start a drag."""
        # Pressed buttons don't include lmb, or tab not selected at start of drag, or
        # not reached min drag distance.
        if ((event.buttons() | QtCore.Qt.LeftButton) != event.buttons()
                or self.drag_info.tab_index == -1 or QtCore.QLineF(
                    event.pos(), self.drag_info.initial_pos).length() < 10):
            return super().mouseMoveEvent(event)

        tab_rect = self.tabRect(self.drag_info.tab_index)

        pixmap = QtGui.QPixmap(tab_rect.size())
        self.render(pixmap, sourceRegion=QtGui.QRegion(tab_rect))
        mime_data = QtCore.QMimeData()
        cursor = QtGui.QCursor(QtCore.Qt.OpenHandCursor)

        drag = QtGui.QDrag(self)
        drag.setMimeData(mime_data)
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos() - self.drag_info.initial_pos)
        drag.setDragCursor(cursor.pixmap(), QtCore.Qt.MoveAction)

        drag.exec_(QtCore.Qt.MoveAction)
Example #15
0
    def draw_path(self, start_port, end_port=None, cursor_pos=None):
        """
        Draws the path between ports.

        Args:
            start_port (PortItem): port used to draw the starting point.
            end_port (PortItem): port used to draw the end point.
            cursor_pos (QtCore.QPointF): cursor position if specified this
                will be the draw end point.
        """
        if not start_port:
            return
        pos1 = start_port.scenePos()
        pos1.setX(pos1.x() + (start_port.boundingRect().width() / 2))
        pos1.setY(pos1.y() + (start_port.boundingRect().height() / 2))
        if cursor_pos:
            pos2 = cursor_pos
        elif end_port:
            pos2 = end_port.scenePos()
            pos2.setX(pos2.x() + (start_port.boundingRect().width() / 2))
            pos2.setY(pos2.y() + (start_port.boundingRect().height() / 2))
        else:
            return

        line = QtCore.QLineF(pos1, pos2)
        path = QtGui.QPainterPath()
        path.moveTo(line.x1(), line.y1())

        if self.viewer_pipe_layout() == PIPE_LAYOUT_STRAIGHT:
            path.lineTo(pos2)
            self.setPath(path)
            return
        else:
            if NODE_LAYOUT_DIRECTION is NODE_LAYOUT_VERTICAL:
                self.__draw_path_vertical(start_port, pos1, pos2, path)
            elif NODE_LAYOUT_DIRECTION is NODE_LAYOUT_HORIZONTAL:
                self.__draw_path_horizontal(start_port, pos1, pos2, path)
Example #16
0
    def mousePressEvent(self, mouse_event):
        """
        Overloaded Mouse Press Event
        Parameters
        ----------
        mouse_event: QGraphicsSceneMouseEvent
            mouse event.
        """
        if mouse_event.button() != QtCore.Qt.LeftButton:
            return
        if self.my_mode == "InsertLine":
            self.line = QtWidgets.QGraphicsLineItem(
                QtCore.QLineF(mouse_event.scenePos(), mouse_event.scenePos()))
            self.line.setPen(QtGui.QPen(self.my_line_color, 2))
            self.addItem(self.line)

        super(DiagramScene, self).mousePressEvent(mouse_event)

        # now display the information about the selected data
        tmp = self.selectedItems()
        if not tmp:
            return
        try:
            odata = tmp[0].my_class.outdata
        except AttributeError:
            return
        parent = self.parent
        text = ''
        for i in odata:
            text += '\n' + i + ' dataset:\n'
            if i == 'Raster' or i == 'Cluster':
                for j in odata[i]:
                    text += '  ' + j.dataid + '\n'
            if i == 'Model3D':
                for j in odata[i][0].lith_list:
                    text += '  ' + j + '\n'
        parent.showdatainfo(text)
Example #17
0
    def resize_line_according_measurements(
        self,
        line,
            associated_measurements):
        normal_line = line.normalVector()
        # sort dict by index

        p1 = geometry.intersect_by_secant(
            QtCore.QPointF(
                associated_measurements[0][0],
                associated_measurements[0][1]),
            normal_line,
            (line,),
            check_line_contain_point=False)
        p2 = geometry.intersect_by_secant(
            QtCore.QPointF(
                associated_measurements[-1][0],
                associated_measurements[-1][1]),
            normal_line,
            (line,),
            check_line_contain_point=False)
        if (len(p1) != 1 or len(p2) != 1):
            LOG.critical("RANSAC ERROR resize_line_according_measurements")
        return QtCore.QLineF(p1[0], p2[0])
Example #18
0
    def try_intersection(cls, diagram, p1, p2, label):
        """
        Try look up intersection and split lines. Return new points, and_lines.
        Points is sorted from p1 to p2.
        """
        new_points = []
        new_lines = []

        iline = QtCore.QLineF(p1.qpointf(), p2.qpointf())
        res_lines = []
        for line in diagram.lines:
            if line.p1 == p1 or line.p1 == p2 or line.p2 == p1 or line.p2 == p2:
                continue
            new_point = QtCore.QPointF()
            if iline.intersect(line.qlinef(),
                               new_point) == QtCore.QLineF.BoundedIntersection:
                new_points.append(new_point)
                res_lines.append(line)

        for i in range(0, len(res_lines)):
            if label == "Add line":
                label = "Add intersected line"
            p, l = diagram.add_new_point_to_line(res_lines[i],
                                                 new_points[i].x(),
                                                 new_points[i].y(), label)
            label = None
            new_lines.append(l)
            new_points[i] = p

        if len(new_points) > 1:
            if p1.x < p2.x:
                new_points.sort(key=lambda p: p.x)
            else:
                new_points.sort(key=lambda p: p.x, reverse=True)

        return new_points, new_lines, label
Example #19
0
 def ulkoinen_voima_nuoli_seinatuki(self):
     '''Luo nuolen osoittamaan ulkoisen voiman paikkaa'''
     voima_viiva = QtGui.QPen(QtCore.Qt.black, 2)
     voima_viiva.setStyle(QtCore.Qt.SolidLine)
     '''Nuolen kärkien koordinaatit seinätuelle'''
     nuoli_piste_1 = QtCore.QPointF(self.palkin_paatypiste - 7, 185)
     nuoli_piste_2 = QtCore.QPointF(self.palkin_paatypiste, 200)
     nuoli_piste_3 = QtCore.QPointF(self.palkin_paatypiste + 7, 185)
     viiva_x = self.palkin_paatypiste
     self.viiva = QGraphicsLineItem(
         QtCore.QLineF(viiva_x, 100, viiva_x, 200))
     '''Luodaan nuoli QPolygonItem olio'''
     self.nuoli_3 = QGraphicsPolygonItem(
         QtGui.QPolygonF([nuoli_piste_1, nuoli_piste_2, nuoli_piste_3]))
     self.nuoli_brush = QtGui.QBrush(1)
     self.nuoli_pencil = QtGui.QPen(QtCore.Qt.black, 2)
     self.nuoli_pencil.setStyle(QtCore.Qt.SolidLine)
     '''Lisätään viiva sekä päiden nuolet sceneen'''
     self.scene.addItem(self.viiva)
     self.scene.addItem(self.nuoli_3)
     self.viiva.hide()
     self.nuoli_3.hide()
     '''Lisätään tieto, että voima on asetettu'''
     Ominaisuudet.ulkoinen_voima(self, 1)
    def drawBackground(self, painter, rect):
        background_brush = QtGui.QBrush(QtGui.QColor(
            10, 10, 10), QtCore.Qt.SolidPattern)  # coloração de fundo
        painter.fillRect(rect, background_brush)
        pen = QtGui.QPen(QtGui.QColor(255, 255, 255))  # Core das linas
        pen.setWidth(1)
        painter.setPen(pen)
        allLines = []
        horigin = int(rect.height() / -1)
        worigin = int(rect.width() / -1)
        self.__screen_size.update({
            "width": rect.width(),
            "height": rect.height()
        })

        # Desenhar as colunas para direita e para esquerda
        for column in range(0, int(rect.height()),
                            self.__screen_size.get("tamanhocelula")):
            line = QtCore.QLineF(worigin, column, int(rect.width()), column)
            allLines.append(line)
        for column in range(0, horigin,
                            self.__screen_size.get("tamanhocelula") * -1):
            line = QtCore.QLineF(worigin, column, int(rect.width()), column)
            allLines.append(line)

        # Desenhar as linhas para cima e para baixo
        for row in range(0, int(rect.width()),
                         self.__screen_size.get("tamanhocelula")):
            line = QtCore.QLineF(row, horigin, row, int(rect.height()))
            allLines.append(line)
        for row in range(0, worigin,
                         self.__screen_size.get("tamanhocelula") * -1):
            line = QtCore.QLineF(row, horigin, row, int(rect.height()))
            allLines.append(line)
        painter.drawLines(allLines)

        #Desenhar as linhas centrais
        pen.setWidth(5)
        painter.setPen(pen)
        line_1 = QtCore.QLineF(0, horigin, 0, int(rect.height()))
        line_2 = QtCore.QLineF(worigin, 0, int(rect.width()), 0)
        painter.drawLines([line_1, line_2])
Example #21
0
    def paint(self, painter, option, widget=None):
        """
        Overloaded paint method.

        Parameters
        ----------
        painter : QPainter
        option : QStyleOptionGraphicsItem
        widget : QWidget, optional
        """
        pi = math.pi
        if self.my_start_item.collidesWithItem(self.my_end_item):
            return

        my_pen = self.pen()
        my_pen.setColor(self.my_color)
        arrow_size = 10.0
        painter.setPen(my_pen)
        painter.setBrush(self.my_color)

        x0, y0 = np.mean(self.my_start_item.np_poly, 0)
        my_start_off = QtCore.QPointF(x0, y0)
        x1, y1 = np.mean(self.my_end_item.np_poly, 0)
        my_end_off = QtCore.QPointF(x1, y1)

        center_line = QtCore.QLineF(self.my_start_item.pos() + my_start_off,
                                    self.my_end_item.pos() + my_end_off)
        end_polygon = self.my_end_item.polygon()
        p1 = end_polygon.first() + self.my_end_item.pos()

        intersect_point = QtCore.QPointF()
        for i in end_polygon:
            p2 = i + self.my_end_item.pos()
            poly_line = QtCore.QLineF(p1, p2)
            intersect_type = poly_line.intersect(center_line, intersect_point)
            if intersect_type == QtCore.QLineF.BoundedIntersection:
                break
            p1 = p2

        self.setLine(
            QtCore.QLineF(intersect_point,
                          self.my_start_item.pos() + my_start_off))
        line = self.line()

        angle = math.acos(line.dx() / line.length())
        if line.dy() >= 0:
            angle = (math.pi * 2.0) - angle

        arrow_p1 = (line.p1() + QtCore.QPointF(
            math.sin(angle + pi / 3) * arrow_size,
            math.cos(angle + pi / 3) * arrow_size))
        arrow_p2 = (line.p1() + QtCore.QPointF(
            math.sin(angle + pi - pi / 3) * arrow_size,
            math.cos(angle + pi - pi / 3) * arrow_size))

        self.arrow_head.clear()
        for point in [line.p1(), arrow_p1, arrow_p2]:
            self.arrow_head.append(point)

        painter.drawLine(line)
        painter.drawPolygon(self.arrow_head)
        if self.isSelected():
            painter.setPen(QtGui.QPen(self.my_color, 1, QtCore.Qt.DashLine))
            my_line = QtCore.QLineF(line)
            my_line.translate(0, 4.0)
            painter.drawLine(my_line)
            my_line.translate(0, -8.0)
            painter.drawLine(my_line)
Example #22
0
    def paint(self, painter, *args, **kwargs):
        self._rect = QtCore.QRectF(0, 0,
                                   len(self.section) * self._bar_width,
                                   self._height)

        #self._bar_width = self._track_view.getBarWidth()
        brush = QtGui.QBrush()
        pen = QtGui.QPen()

        width = self._bar_width * len(self.section)
        height = self._height - 1

        # draw section box...
        brush.setColor(self._section_color)
        brush.setStyle(Qt.SolidPattern)
        painter.setBrush(brush)
        if self.isSelected():
            pen.setColor(QtGui.QColor('white'))
            pen.setWidth(2)
            painter.setPen(pen)
            self.setZValue(5)
        else:
            painter.setPen(Qt.NoPen)
            self.setZValue(1)
        painter.drawRect(0, 0, width, height)

        # draw track...
        brush.setColor(self._backgroud_color)
        brush.setStyle(Qt.SolidPattern)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QtCore.QRect(0, 15, width, height - 15), brush)

        pen.setColor(QtGui.QColor("black"))
        pen.setCapStyle(Qt.FlatCap)
        pen.setWidth(1)
        painter.setPen(pen)
        if not self.section.blank and len(self.section.name) * 5 < len(
                self.section) * self._bar_width:
            painter.drawText(10, 13, self.section.name)

        # draw bar lines...
        for i in range(0, len(self.section)):
            x = i * self._bar_width
            if i % self.section.params['length'] == 0 and self.section.params[
                    'loop_num'] > 1:
                painter.drawLine(x, 0, x, height)
            elif (i+self.section.params['loop_alt_len']) % self.section.params['length'] == 0 \
                 and self.section.params['loop_num'] > 1:
                painter.drawLine(x, 5, x, height)
                painter.drawLine(
                    x, 5,
                    x + self.section.params['loop_alt_len'] * self._bar_width,
                    5)
            elif self._bar_width > 40:
                pen.setColor(QtGui.QColor('#303030'))
                painter.setPen(pen)
                painter.drawLine(x, 15, x, height)
                pen.setColor(QtGui.QColor("black"))
                painter.setPen(pen)

        # fill in the notes...
        pen.setColor(self._main_note_color)
        pen.setWidth(2)
        painter.setPen(pen)

        lines = []

        for i, measure in enumerate(self.section.flatMeasures):
            if self.section.blank:
                continue

            #painter.drawText(self._bar_width*(i+1)-15, 25, str(measure.id_))

            if self._bar_width > 10:
                if not measure or (measure.isEmpty()
                                   and not measure.genRequestSent):
                    # draw red x...
                    painter.drawText(self._bar_width * i + 5, 25, "X")
                    continue

                if measure.genRequestSent:
                    painter.drawText(self._bar_width * i + 5, 25, "O")
                    continue

            for j, note in enumerate(measure.getNotes()):
                y = height - note[0] + 20
                x1 = self._bar_width * (i + note[1] / 96)
                x2 = self._bar_width * (i + note[2] / 96) - 1

                # for small scales, only draw every second note
                if (x2 - x1 > 0) and (x2 - x1 > 2 or j % 2 == 0):
                    lines.append(QtCore.QLineF(x1, y, x2, y))

        painter.drawLines(lines)
    def paintEvent(self, QPaintEvent):
        if self._qImage is not None:
            painter = QtGui.QPainter(self)

            transform = QtGui.QTransform()
            transform.scale(self._zoom, self._zoom)
            painter.setTransform(transform, False)

            painter.drawImage(0, 0, self._qImage)

            if self._leftClickPosition is not None:
                painter.setPen(QtGui.QPen(QtCore.Qt.red))
                painter.pen().setWidth(1)

                cornerCalcOffset = int(
                    Application.Settings.MagnifierWindowSettings.gridSize /
                    2) + 1

                x, y = self._leftClickPosition

                # vertical line
                painter.drawLine(
                    QtCore.QLineF(x + 0.5, 0.0, x + 0.5,
                                  (self.height - 1) / self._zoom))

                # horizontal line
                painter.drawLine(
                    QtCore.QLineF(0.0, y + 0.5, (self.width - 1) / self._zoom,
                                  y + 0.5))

                # +1 because we need to take into account the thickness of the rectangle itself
                # we want its contents inside to be frameGridSize^2
                painter.drawRect(
                    QtCore.QRectF(
                        x + 0.5 - cornerCalcOffset, y + 0.5 - cornerCalcOffset,
                        Application.Settings.MagnifierWindowSettings.gridSize +
                        1,
                        Application.Settings.MagnifierWindowSettings.gridSize +
                        1))

            if self._rightClickLastPositions is not None:
                painter.setPen(QtGui.QPen(QtCore.Qt.blue))
                painter.pen().setWidth(1)

                if Application.Settings.RightClickPointerSettings.showClickOrder:
                    font = QtGui.QFont("Arial")
                    font.setPointSize(
                        Application.Settings.RightClickPointerSettings.
                        clickOrderFontSize)
                    painter.setFont(font)
                    fontMetrics = QtGui.QFontMetrics(font)

                cornerCalcOffset = int(
                    Application.Settings.RightClickPointerSettings.
                    aroundClickSquareSize / 2) + 1

                for clickNumber in range(len(self._rightClickLastPositions)):
                    x, y = self._rightClickLastPositions[clickNumber]

                    # +1 because we need to take into account the thickness of the rectangle itself
                    # we want its contents inside to be frameGridSize^2
                    painter.drawRect(
                        QtCore.QRectF(
                            x + 0.5 - cornerCalcOffset,
                            y + 0.5 - cornerCalcOffset,
                            Application.Settings.RightClickPointerSettings.
                            aroundClickSquareSize + 1,
                            Application.Settings.RightClickPointerSettings.
                            aroundClickSquareSize + 1))

                    if Application.Settings.RightClickPointerSettings.showClickOrder:
                        clickNumberStr = str(clickNumber + 1)
                        horizontalAdvance = fontMetrics.horizontalAdvance(
                            clickNumberStr, len(clickNumberStr))

                        painter.drawText(x - horizontalAdvance / 2 + 1,
                                         y + fontMetrics.ascent() / 2 - 1,
                                         clickNumberStr)

                    # draw a point in the center to know the exact selected pixel
                    painter.setPen(QtGui.QPen(QtCore.Qt.red))
                    painter.drawPoint(QtCore.QPointF(x + 0.5, y + 0.5))
                    painter.setPen(QtGui.QPen(QtCore.Qt.blue))

            if self._overlayData is not None:
                painterPath, colorName, width = self._overlayData
                color = QtGui.QColor()
                color.setNamedColor(colorName)
                pen = QtGui.QPen(color)
                pen.setWidth(width)
                painter.setPen(pen)
                painter.drawPath(painterPath)

        self.finishedPaintingSignal.emit()
Example #24
0
 def line(self):
     return QtCore.QLineF(self.line1.line().x1(),
                          self.line1.line().y1(),
                          self.line2.line().x2(),
                          self.line2.line().y2())
Example #25
0
 def drawSketch(self, prev_pt, curr_pt):
     lineItem = QtWidgets.QGraphicsLineItem(QtCore.QLineF(prev_pt, curr_pt))
     lineItem.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine))
     self.addItem(lineItem)
Example #26
0
 def drawMask(self, prev_pt, curr_pt):
     lineItem = QtWidgets.QGraphicsLineItem(QtCore.QLineF(prev_pt, curr_pt))
     # rect
     lineItem.setPen(QtGui.QPen(QtCore.Qt.white, 12, QtCore.Qt.SolidLine))
     self.addItem(lineItem)
Example #27
0
 def drawStroke(self, prev_pt, curr_pt):
     lineItem = QtWidgets.QGraphicsLineItem(QtCore.QLineF(prev_pt, curr_pt))
     lineItem.setPen(
         QtGui.QPen(QtGui.QColor(self.stk_color), 4, QtCore.Qt.SolidLine))
     self.addItem(lineItem)
Example #28
0
 def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
     for i, point in enumerate(self.poly.points):
         if QtCore.QLineF(point.to_QPoint() + self.center, event.pos()).length() < 20:
             self.mouse_grabbed = True
             self.poly.ci = i
             break
Example #29
0
    def paint(self, painter, option, widget):
        """

        :param painter:
        :param option:
        :param widget:
        :raise:
        """
        if ctrl.pressed is self:
            pass
        c = self.contextual_color()
        painter.setPen(c)
        dx = self.start_point[0] - self.end_point[0]
        dy = self.start_point[1] - self.end_point[1]
        l = QtCore.QLineF(dx, dy, 0, 0)

        if self._hovering:
            if len(self.host.trees) != 1:
                painter.drawLine(l)
                painter.save()
                painter.setBrush(ctrl.cm.ui())
                painter.rotate(20)
                draw_leaf(painter, 0, end_spot_size / 2, end_spot_size)
                painter.restore()
                draw_plus(painter, 4, 0)
                return
            else:
                top = list(self.host.trees)[0].top
                lmx, lmy = top.magnet(5)
                scene_point = QtCore.QPointF(lmx, lmy)
                end_point = self.mapFromScene(scene_point)
                path = QtGui.QPainterPath(QtCore.QPointF(dx, dy))
                path.quadTo(QtCore.QPointF(end_point.x() - 200, end_point.y()),
                            end_point)
                painter.drawPath(path)
                l = QtCore.QLineF(
                    QtCore.QPointF(end_point.x() - 200, end_point.y()),
                    end_point)
        else:
            painter.drawLine(l)

        l2x = l.p2().x()
        l2 = l.p2()
        l2y = l.p2().y()
        head_size = 8.0
        back = head_size / -2
        # Draw the arrows if there's enough room.
        ll = l.length()
        if ll >= 1 and ll + back > 0:
            angle = math.acos(l.dx() / ll)  # acos has to be <= 1.0
        else:
            return
        prop = back / ll
        if l.dy() >= 0:
            angle = (math.pi * 2.0) - angle
        destArrowP1 = QtCore.QPointF(
            (math.sin(angle - math.pi / 3) * head_size) + l2x,
            (math.cos(angle - math.pi / 3) * head_size) + l2y)
        destArrowP2 = QtCore.QPointF(
            (math.sin(angle - math.pi + math.pi / 3) * head_size) + l2x,
            (math.cos(angle - math.pi + math.pi / 3) * head_size) + l2y)
        l2c = QtCore.QPointF(l.dx() * prop + l2x, l.dy() * prop + l2y)
        painter.setBrush(c)
        painter.drawPolygon(
            QtGui.QPolygonF([l2, destArrowP1, l2c, destArrowP2]))
Example #30
0
    def drawPlants(self):
        size = 20
        hor_space = 40
        ver_space = 100
        self.scene.clear()
        for y in range(4):
            for x in range(16):
                plant_type = self.fieldConfig.item((y, x))
                r = QtCore.QRectF(QtCore.QPointF(x * hor_space, y * ver_space),
                                  QtCore.QSizeF(size, size))
                self.scene.addRect(r, self.blackPen,
                                   self.BrushList[plant_type])
                detected_plant_type = self.detectedFieldConfig.item((y, x))
                self.scene.addEllipse(x * hor_space, y * ver_space + 30, size,
                                      size, self.blackPen,
                                      self.BrushList[detected_plant_type])

        # separation line
        self.scene.addLine(
            QtCore.QLineF(16.4 * hor_space, 0, 16.4 * hor_space, 350))
        # draw a legend
        for i in range(3 if self.level == 0 else 5):
            r = QtCore.QRectF(
                QtCore.QPointF(17 * hor_space, i * ver_space / 2),
                QtCore.QSizeF(size, size))
            self.scene.addRect(r, self.blackPen, self.BrushList[i])
            t = self.scene.addText(self.colorNames[i], QFont("Helvetica"))
            t.setPos(18 * hor_space, i * ver_space / 2)
        i = 3 if self.level == 0 else 5
        self.scene.addEllipse(17 * hor_space, i * ver_space / 2, size, size,
                              self.blackPen, self.BrushList[5])
        t = self.scene.addText(self.colorNames[5], QFont("Helvetica"))
        t.setPos(18 * hor_space, i * ver_space / 2)

        #calculate the score
        true_count_per_row = np.count_nonzero(
            np.logical_and(self.fieldConfig > 0, self.fieldConfig < 5),
            axis=1) + np.count_nonzero(self.fieldConfig == 3, axis=1)
        robot_count_per_row = np.count_nonzero(
            np.logical_and(self.detectedFieldConfig > 0,
                           self.detectedFieldConfig < 5),
            axis=1) + np.count_nonzero(self.detectedFieldConfig == 3, axis=1)
        # plant density score
        error_per_row = np.abs(true_count_per_row - robot_count_per_row)
        density_score = np.zeros(4, dtype=np.int32)
        density_score[error_per_row == 0] = 5
        density_score[error_per_row == 1] = 3
        density_score[error_per_row == 2] = 1
        correct_detections = self.fieldConfig[np.equal(
            self.fieldConfig, self.detectedFieldConfig)]
        points_for_empty_or_stress = 3 if self.level == 0 else 2
        detection_score = points_for_empty_or_stress * len(
            correct_detections[(correct_detections == 0) |
                               (correct_detections == 1)])

        if self.level == 1:
            detection_score += 4 * len(
                correct_detections[(correct_detections == 3) |
                                   (correct_detections == 4)])

        print(detection_score, density_score.sum())
        score = detection_score + density_score.sum()
        self.LCD.display(score)