Ejemplo n.º 1
1
    def loadImage(self, xFactor, yFactor):
        newImg = QImage()
        newImg.load(self.photoFileManager.getCurPhotoFilename())
        newImgInfo = self.photoFileManager.getCurPhotoInfo()
        transform = QTransform()
        transform.rotate(newImgInfo.rotationAngle)
        interImg = newImg.transformed(transform, Qt.SmoothTransformation)
        xReqdSize = self.cellSize.width() * xFactor + self.xBetweenPics * (xFactor-1)
        yReqdSize = self.cellSize.height() * yFactor + self.yBetweenPics * (yFactor-1)
        inter2Img = interImg.scaled(QSize(xReqdSize,yReqdSize), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
        finalImg = inter2Img.copy(0,0,xReqdSize,yReqdSize)
#        print("XY Size", xFactor, yFactor, xReqdSize,yReqdSize)
        return (finalImg, newImgInfo)
Ejemplo n.º 2
0
 def resizeEvent(self, event):
     sceneWidth = min(event.size().width(), event.size().height())
     trans = QTransform()
     trans.scale(sceneWidth / self.initialSceneWidth,
                 sceneWidth / self.initialSceneWidth)
     self.setTransform(trans)
     self.centerOn(sceneWidth / 2.0, sceneWidth / 2.0)
Ejemplo n.º 3
0
def _image(file, sub_folder, rotate=None):
    pixmap = QPixmap(os_path_join(_BASE_PATH, sub_folder, file))
    if rotate is None:
        return pixmap
    transform = QTransform()
    transform.rotate(rotate)
    return pixmap.transformed(transform)
Ejemplo n.º 4
0
    def setupMatrix(self):
        scale = 2.0 ** ((self.zoomLevel - 250) / 50.0)

        transform = QTransform()
        transform.scale(scale, scale)

        self.graphicsView.setTransform(transform)
Ejemplo n.º 5
0
    def init (self):
        self.m_scaleX = self.width() / self.m_originalWidth
        self.m_scaleY = self.height() / self.m_originalHeight


        self.m_itemHand = QGraphicsSvgItem(":/qfi/images/vsi/vsi_hand.svg")
        self.m_itemHand.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemHand.setZValue( self.m_handZ )
        self.m_itemHand.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemHand.setTransformOriginPoint( self.m_originalVsiCtr )
        self.m_scene.addItem (self.m_itemHand)

        self.m_itemFace = QGraphicsSvgItem(":/qfi/images/vsi/vsi_face.svg")
        self.m_itemFace.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemFace.setZValue( self.m_faceZ )
        self.m_itemFace.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemFace.setTransformOriginPoint( self.m_originalVsiCtr )
        self.m_scene.addItem (self.m_itemFace)


        self.m_itemCase = QGraphicsSvgItem(":/qfi/images/vsi/vsi_case.svg")
        self.m_itemCase.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemCase.setZValue( self.m_caseZ )
        self.m_itemCase.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemCase.setTransformOriginPoint( self.m_originalVsiCtr )
        self.m_scene.addItem (self.m_itemCase)

        self.centerOn (self.width()/2, self.height()/2)

        self.updateView()
Ejemplo n.º 6
0
 def wind_icon_direction(self):
     transf = QTransform()
     angle = self.weatherdata['Wind'][2]
     logging.debug('Wind degrees direction: ' + angle)
     transf.rotate(int(float(angle)))
     rotated = self.wind_icon.transformed(transf, mode=Qt.SmoothTransformation)
     self.wind_icon_label.setPixmap(rotated)
Ejemplo n.º 7
0
    def paintEvent(self, event):
        """QToolBar.paintEvent reimplementation
        Draws buttons, dock icon and text
        """
        rect = self._spacer.rect()

        painter = QPainter(self)

        transform = QTransform()
        transform.translate(self._spacer.pos().x(), self._spacer.pos().y())
        painter.setTransform(transform)

        """ Not supported currently
        if  self._dock.features() & QDockWidget.DockWidgetVerticalTitleBar :
            transform = QTransform()

            rect.setSize(QSize(rect.height(), rect.width()))
            transform.rotate(-90)
            transform.translate(-rect.width(), 0)

            painter.setTransform(transform)
        """

        # icon / title
        optionB = QStyleOptionButton()
        optionB.initFrom(self._dock)
        optionB.rect = rect
        optionB.text = self._dock.windowTitle()
        optionB.iconSize = self.iconSize()
        optionB.icon = self._dock.windowIcon()

        self.style().drawControl(QStyle.CE_PushButtonLabel, optionB, painter, self._dock)
Ejemplo n.º 8
0
def ParseTransformAttrib(s):
  # where s is an SVG transform attribute such as "translate(-2,1) matrix(0 1 2 3 4 5)"
  # return a list of QTransforms
  xforms = []
  s = s.lower()
  while s:
    s = re.sub(r'^\s+,?\s+', '', s)  # remove leading WS,WS
    m = re.match(r'\s*(\w+)\s*\(((\s*[0-9e.+-]+\s*,?)+)\)', s) # match identifier(numbers) clause
    if m:
      values = SplitFloatValues(m.group(2))
      if m.group(1) == 'translate':
        if len(values) == 1: values.append(0)
        xforms.append( QTransform.fromTranslate(*values) )
      elif m.group(1) == 'scale':
        if len(values) == 1: values.append(values[0])
        xforms.append( QTransform.fromScale(*values) )
      elif m.group(1) == 'rotate':
        xforms.append( QTransform().rotate(values[0]) )  # TODO: handle cx,cy values
      elif m.group(1) == 'matrix':
        logger.trace('matrix({}): m.group(2) = {}', values, m.group(2))
        xforms.append( QTransform( values[0], values[1], 0
                                 , values[2], values[3], 0
                                 , values[4], values[5], 1) )
      # TODO: handle skewX and skewY
      else: logger.warning('unrecognized transform: {}', m.group())
      s = s[m.end()+1:]
    else:
      if s: logger.warning('unparsed transform: {}', s)
      break
  return xforms
Ejemplo n.º 9
0
    def _get_selected_edge(self, pos: QPointF, transform: QTransform, horizontal_selection: bool):
        x1, x2 = self.x, self.x + self.width
        y1, y2 = self.y, self.y + self.height
        x, y = pos.x(), pos.y()

        spacing = 5
        spacing /= transform.m11() if horizontal_selection else transform.m22()

        if horizontal_selection:
            x1a, x1b = x1 - spacing, x1 + spacing
            y1a, y1b = y1, y2
            x2a, x2b = x2 - spacing, x2 + spacing
            y2a, y2b = y1, y2
        else:
            x1a, x1b, x2a, x2b = x1, x2, x1, x2
            y1a, y1b = min(y1 - spacing, y1 + spacing), max(y1 - spacing, y1 + spacing)
            y2a, y2b = min(y2 - spacing, y2 + spacing), max(y2 - spacing, y2 + spacing)

        if x1a < x < x1b and y1a < y < y1b:
            self.selected_edge = 0
            return 0

        if x2a < x < x2b and y2a < y < y2b:
            self.selected_edge = 1
            return 1

        self.selected_edge = None
        return None
Ejemplo n.º 10
0
    def rotate(self):
        t = QTransform()

        # for x in range (0, 150):
        t.rotate(-1)
        self.label.setPixmap(self.label.pixmap().transformed(t))


        print("FINISHED")
Ejemplo n.º 11
0
 def zoom(self, factor, pos):
     self.recenter(pos)
     p = self._transform.inverted()[0].map(self.rect().center())
     test = QTransform(self._transform)
     test.scale(factor, factor)
     # check if the bounding rectangle does not enclose the view
     # refuse to zoom out (factor < 1) if this is the case
     # XXX TODO
     self._transform.scale(factor, factor)
     self.recenter(p, True)
Ejemplo n.º 12
0
 def mapTextureBasedOnZoom(self, brush):
     if brush.texture().width() > 0 and brush.texture().height() > 0:
         brush_trans = QTransform()
         brush_trans.translate(self.__center_x - self.__width * 0.5,
                 self.__center_y - self.__height * 0.5)
         brush_trans.scale(self.__width/float(brush.texture().width()),
                 self.__height/float(brush.texture().height()))
         brush.setTransform(brush_trans)
 
     self.setBrush(brush)
Ejemplo n.º 13
0
    def rotatePlayer(self, direction):
        """
        Function responsible for rotating players icon.
        """

        rotation = QTransform()

        if direction == 'up':
            rotation.rotate(0)
        elif direction == 'right':
            rotation.rotate(90)
        elif direction == 'down':
            rotation.rotate(180)
        elif direction == 'left':
            rotation.rotate(270)

        self.use_this_pixmap = \
            self.nurse_pixmap_base.transformed(rotation)
        self.nurse_pixmap = \
            self.nurse_pixmap_base.transformed(rotation)
        self.nurse_left_pixmap = \
            self.nurse_left_pixmap_base.transformed(rotation)
        self.nurse_right_pixmap = \
            self.nurse_right_pixmap_base.transformed(rotation)

        """
Ejemplo n.º 14
0
	def mouseMoveEvent(self, ev):
		if self.mode == MODE_MOVE:
			return QGraphicsItem.mouseMoveEvent(self, ev)

		center = self.transform().map(self.boundingRect().center())
		origToCenter = self.origin - center
		originScale = vectorLength(origToCenter)
		origAngle = math.atan2(origToCenter.y(), origToCenter.x())

		newPt = self.transform().map(ev.pos())
		newToCenter = newPt - center
		newScale = vectorLength(newToCenter)
		newAngle = math.atan2(newToCenter.y(), newToCenter.x())

		# build transform
		t = QTransform()
		t.translate(center.x(), center.y())
		if self.mode == MODE_ROT:
			self._angle = math.degrees(newAngle - origAngle)
		t.rotate(self._angle)

		if self.mode == MODE_ZOOM:
			self._scale = newScale / originScale
		t.scale(self._scale, self._scale)
		t.translate(-center.x(), -center.y())
		self.setTransform(t)
Ejemplo n.º 15
0
 def resizeEvent(self, event):
     self.setUpdatesEnabled(False)
     super().resizeEvent(event)
     # center scene in viewport
     r = self.rect()
     t = QTransform()
     t.translate(-r.width() / 2, -r.height() / 2)
     r = QRectF(QPointF(r.x(), r.y()) * t, QSizeF(r.width(), r.height()))
     self.setSceneRect(r)
     self.__resizeDelayTimer.start(self.resizeUpdateDelay)
     self.setUpdatesEnabled(True)
Ejemplo n.º 16
0
 def transform(self):
     try:
         return self.__dict__['transform'] if self.scale else QTransform()
     except KeyError:
         transform = QTransform()
         image = self.client.image
         if image is not None and not image.isNull():
             scale = min(self.width()/image.width(), self.height()/image.height())
             transform.translate((self.width() - image.width()*scale)/2, (self.height() - image.height()*scale)/2)
             transform.scale(scale, scale)
             transform = self.__dict__.setdefault('transform', transform)
         return transform
Ejemplo n.º 17
0
def visibleIn(area, object, renderer):
    boundingRect = renderer.boundingRect(object)
    if (object.rotation() != 0):
        # Rotate around object position
        pos = renderer.pixelToScreenCoords_(object.position())
        boundingRect.translate(-pos)
        transform = QTransform()
        transform.rotate(object.rotation())
        boundingRect = transform.mapRect(boundingRect)
        boundingRect.translate(pos)

    return intersects(area, boundingRect)
Ejemplo n.º 18
0
    def _updateSequenceText(self):
        seq_item = self._seq_item
        is_on_top = self._is_on_top
        index = self._insertion.idx()
        base_text = self._seq_text
        font = styles.SEQUENCEFONT
        seq_font_h = styles.SEQUENCEFONTH
        insert_w = styles.INSERTWIDTH
        seq_font_char_w = styles.SEQUENCEFONTCHARWIDTH
        # draw sequence on the insert
        if base_text:  # only draw sequences if they exist i.e. not None!
            len_BT = len(base_text)
            if is_on_top:
                angle_offset = 0
            else:
                angle_offset = 180
            if len_BT > 20:
                base_text = base_text[:17] + '...'
                len_BT = len(base_text)
            fraction_arc_len_per_char = (1.0 - 2.0*_FRACTION_INSERT_TO_PAD) / (len_BT + 1)
            seq_item.setPen(QPen(Qt.NoPen))
            seq_item.setBrush(QBrush(Qt.black))

            seq_path = QPainterPath()
            loop_path = self.path()
            for i in range(len_BT):
                frac = _FRACTION_INSERT_TO_PAD + (i+1)*fraction_arc_len_per_char
                pt = loop_path.pointAtPercent(frac)
                tang_ang = loop_path.angleAtPercent(frac)

                temp_path = QPainterPath()
                # 1. draw the text
                temp_path.addText(0, 0, font, base_text[i if is_on_top else -i-1])
                # 2. center it at the zero point different for top and bottom
                # strands
                if not is_on_top:
                    temp_path.translate(0, -seq_font_h - insert_w)

                temp_path.translate(QPointF(-seq_font_char_w / 2.,
                                          -2 if is_on_top else seq_font_h))


                mat = QTransform()
                # 3. rotate it
                mat.rotate(-tang_ang + angle_offset)

                rotated_path = mat.map(temp_path)
                # 4. translate the rotate object to it's position on the part
                rotated_path.translate(pt)
                seq_path.addPath(rotated_path)
            # end for
            seq_item.setPath(seq_path)
 def loadImage(self):
     self.newImg = QImage()
     self.newImg.load(self.photoFileManager.getCurPhotoFilename())
     self.newImgInfo = self.photoFileManager.getCurPhotoInfo()
     transform = QTransform()
     transform.rotate(self.newImgInfo.rotationAngle)
     self.interImg = self.newImg.transformed(transform, Qt.SmoothTransformation)
     # xReqdSize = self.cellSize.width() * xFactor + self.xBetweenPics * (xFactor-1)
     # yReqdSize = self.cellSize.height() * yFactor + self.yBetweenPics * (yFactor-1)
     self.inter2Img = self.interImg.scaled(QSize(self.width(),self.height()),
                                                 Qt.KeepAspectRatio, Qt.SmoothTransformation)
     # finalImg = interImg.copy(0,0,xReqdSize,yReqdSize)
     # print("XY Size", xFactor, yFactor, xReqdSize,yReqdSize)
     return self.inter2Img, self.newImgInfo
Ejemplo n.º 20
0
    def draw_frequency_marker(self, x_pos, frequency):
        if frequency is None:
            self.clear_frequency_marker()
            return

        y1 = self.sceneRect().y()
        y2 = self.sceneRect().y() + self.sceneRect().height()

        if self.frequency_marker is None:
            pen = QPen(constants.LINECOLOR, 0)
            self.frequency_marker = [None, None]
            self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen)
            self.frequency_marker[1] = self.addSimpleText("")
            self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR))
            font = QFont()
            font.setBold(True)
            font.setPointSize(int(font.pointSize() * 1.25)+1)
            self.frequency_marker[1].setFont(font)

        self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2)
        scale_x, scale_y = self.__calc_x_y_scale(self.sceneRect())
        self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False)
        self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3))
        font_metric = QFontMetrics(self.frequency_marker[1].font())
        text_width = font_metric.width("Tune to") * scale_x
        text_width += (font_metric.width(" ") * scale_x) / 2
        self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
Ejemplo n.º 21
0
    def mouseMoveEvent(self, event):
        if self.__dragActive:
            mousePos = self.view.mapToScene(self.view.mapFromGlobal(QCursor.pos()))
            vec1 = QVector2D(mousePos)
            vec1.normalize()
            trans = QTransform()
            trans.rotate(self.rotation())
            vec2 = QVector2D(self.p2 * trans)
            vec2.normalize()
            angle = math.acos(max(-1, min(1, QVector2D.dotProduct(vec1, vec2)))) * 180 / math.pi

            # clockwise rotation
            if vec1.y() * vec2.x() < vec1.x() * vec2.y():
                angle *= -1

            angle = (self.rotation() + angle) % 360
            self.setRotation(angle)
Ejemplo n.º 22
0
    def new_absolute_zoom(self, factor):
        """Sets a new absolute zoom and emits viewport_changed.
        """
        f = factor
        scene_rect = self.scene().sceneRect()   # Scene
        view_rect = self.viewport().rect()      # Available space
        # The size of the scene if the new transform is applied
        t_scene_rect = QTransform.fromScale(f, f).mapRect(scene_rect)

        if (t_scene_rect.width() < view_rect.width() and
                t_scene_rect.height() < view_rect.height()):
            # The user wants to zoom out so that the image is smaller than the
            # view
            self.zoom_home()
        else:
            f = min(self.MAXIMUM_ZOOM, f)
            msg = 'Change absolute zoom from [{0}] to [{1}]'
            debug_print(msg.format(self.absolute_zoom, f))

            selected = self.scene().selectedItems()
            if not selected:
                # No selection so we want to centre on the mouse cursor, if it
                # is within the view. We need to get the mouse position in
                # scene coords before applying the zoom.
                mouse_pos = self.mapFromGlobal(QCursor.pos())
                if self.rect().contains(mouse_pos, proper=True):
                    mouse_pos = self.mapToScene(mouse_pos)
                else:
                    mouse_pos = None

            self.setTransform(QTransform.fromScale(f, f))

            if selected:
                # Centre on selected items
                self.centerOn(
                    unite_rects(i.sceneBoundingRect() for i in selected).center()
                )
            elif mouse_pos:
                # Centre on mouse position
                self.centerOn(mouse_pos)
            else:
                # Default behaviour is fine
                pass

        self.viewport_changed.emit(self.normalised_scene_rect())
Ejemplo n.º 23
0
    def _fetch_tile_layer(self, timestamp, ims, transform, tile_nr, stack_id, ims_req, cache):
        """
        Fetch a single tile from a layer (ImageSource).

        Parameters
        ----------
        timestamp
            The timestamp at which ims_req was created
        ims
            The layer (image source) we're fetching from
        transform
            The transform to apply to the fetched data, before storing it in the cache
        tile_nr
            The ID of the fetched tile
        stack_id
            The stack ID of the tile we're fetching (e.g. which T-slice and Z-slice this tile belongs to)
        ims_req
            A request object (e.g. GrayscaleImageRequest) with a wait() method that produces an item of
            the appropriate type for the layer (i.e. either a QImage or a QGraphicsItem)
        cache
            The value of self._cache at the time the ims_req was created.
            (The cache can be replaced occasionally. See TileProvider._onSizeChanged().)
        """
        try:
            try:
                with cache:
                    layerTimestamp = cache.layerTimestamp(stack_id, ims, tile_nr)
            except KeyError:
                # May not be a timestamp yet (especially when prefetching)
                layerTimestamp = 0

            tile_rect = QRectF(self.tiling.imageRects[tile_nr])

            if timestamp > layerTimestamp:
                img = ims_req.wait()
                if isinstance(img, QImage):
                    img = img.transformed(transform)
                elif isinstance(img, QGraphicsItem):
                    # FIXME: It *seems* like applying the same transform to QImages and QGraphicsItems
                    #        makes sense here, but for some strange reason it isn't right.
                    #        For QGraphicsItems, it seems obvious that this is the correct transform.
                    #        I do not understand the formula that produces 'transform', which is used for QImage tiles.
                    img.setTransform(QTransform.fromTranslate(tile_rect.left(), tile_rect.top()), combine=True)
                    img.setTransform(self.tiling.data2scene, combine=True)
                else:
                    assert False, "Unexpected image type: {}".format(type(img))

                with cache:
                    try:
                        cache.updateTileIfNecessary(stack_id, ims, tile_nr, timestamp, img)
                    except KeyError:
                        pass

                if stack_id == self._current_stack_id and cache is self._cache:
                    self.sceneRectChanged.emit(tile_rect)
        except BaseException:
            sys.excepthook(*sys.exc_info())
Ejemplo n.º 24
0
 def setHeading(self, heading):
     xForm = QTransform()
     xForm.translate(self.__center_x, self.__center_y)
     xForm.rotate(math.degrees(heading))
     xForm.translate(-self.__center_x, -self.__center_y)
     self.setTransform(xForm)
     
     self.mapTextureBasedOnZoom(self.brush())
Ejemplo n.º 25
0
    def textureRect(self, rect_tile):
        tile_info = rect_tile.data(0)

        if tile_info is None:
            return False

        pm = QPixmap(self.__tiler.tile_to_path(tile_info))  
        if pm.width() != 256:
            #print("Probably didn't get tile:", next_tile_info.x, next_tile_info.y, "\n")
            #TODO: Attempt to texture with a lower res tile
            #Bear in mind that you will have to take Mercator projection into
            #account on the lower res tile.
            
            #First Attempt: didn't work
            #if tile_info.zoom <= self.__tiler.get_min_zoom():
            #    return False
            #
            #find colocated lower res tile
            #(lat,lon) = tile_info.coord()
            #tile_info2 = self.__tiler.coord_to_tile(lat,lon, tile_info.zoom-1)
            #rect_tile.setData(0, tile_info2)
            #print("prev tile: ", tile_info.tile, tile_info.coord())
            #return self.textureRect(rect_tile, depth + 1)

            #until such time as we can pull lower res tiles and figure out
            #which area to render on a rectangle, skip:
            return False

        topLeft = rect_tile.boundingRect().topLeft()
        bottomRight = rect_tile.boundingRect().bottomRight()   
       
        width = bottomRight.x() - topLeft.x()
        height = bottomRight.y() - topLeft.y()

        brush_trans = QTransform()        
        brush_trans.translate(topLeft.x(), topLeft.y())
        brush_trans.scale(width/256.0, height/256.0)

        qb = QBrush(pm)
        qb.setTransform(brush_trans)
        rect_tile.setBrush(qb)
   
        return True
Ejemplo n.º 26
0
def _QGraphicssItem_scale(self, *args):
    if args:
        warnings.warn(
            "QGraphicsItem.scale(sx, sy) is obsolete and removed in PyQt5. "
            "Use setTransform(QTransform.fromScale(sx, sy), True) instead.",
            DeprecationWarning,
            stacklevel=2
        )
        self.setTransform(QTransform.fromScale(*args), True)
    else:
        return _QGraphicsItem_scale1(self)
Ejemplo n.º 27
0
def objectTransform(object, renderer):
    transform = QTransform()
    if (object.rotation() != 0):
        pos = renderer.pixelToScreenCoords_(object.position())
        transform = rotateAt(pos, object.rotation())

    offset = object.objectGroup().offset()
    if not offset.isNull():
        transform *= QTransform.fromTranslate(offset.x(), offset.y())
        
    return transform
Ejemplo n.º 28
0
    def timerEvent(self, event):
        axelDistance = 54.0
        wheelsAngleRads = (self.wheelsAngle * math.pi) / 180
        turnDistance = math.cos(wheelsAngleRads) * axelDistance * 2
        turnRateRads = wheelsAngleRads / turnDistance
        turnRate = (turnRateRads * 180) / math.pi
        rotation = self.speed * turnRate

        self.setTransform(QTransform().rotate(rotation), True)
        self.setTransform(QTransform.fromTranslate(0, -self.speed), True)
        self.update()
Ejemplo n.º 29
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self._transform = QTransform()
     # set up transform
     self._transform.translate(0, 0)
     # set to 100 px = 1 inch
     self._transform.scale(100.0/Coord.inchToSch(1), -100.0/Coord.inchToSch(1))
     self._mousePos = QPoint()
     self._wheelAngle = 0
     self._ctrl = None
     self.setMouseTracking(True)
     self.setFocusPolicy(Qt.StrongFocus)
Ejemplo n.º 30
0
    def init (self):
        self.m_scaleX = self.width() / self.m_originalWidth
        self.m_scaleY = self.height() / self.m_originalHeight


        self.m_itemBack = QGraphicsSvgItem(":/qfi/images/adi/adi_back.svg")
        self.m_itemBack.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemBack.setZValue( self.m_backZ )
        self.m_itemBack.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemBack.setTransformOriginPoint( self.m_originalAdiCtr )
        self.m_scene.addItem (self.m_itemBack)

        self.m_itemFace = QGraphicsSvgItem(":/qfi/images/adi/adi_face.svg")
        self.m_itemFace.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemFace.setZValue( self.m_faceZ )
        self.m_itemFace.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemFace.setTransformOriginPoint( self.m_originalAdiCtr )
        self.m_scene.addItem (self.m_itemFace)

        self.m_itemRing = QGraphicsSvgItem(":/qfi/images/adi/adi_ring.svg")
        self.m_itemRing.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemRing.setZValue( self.m_ringZ )
        self.m_itemRing.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemRing.setTransformOriginPoint( self.m_originalAdiCtr )
        self.m_scene.addItem (self.m_itemRing)


        self.m_itemCase = QGraphicsSvgItem(":/qfi/images/alt/alt_case.svg")
        self.m_itemCase.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemCase.setZValue( self.m_caseZ )
        self.m_itemCase.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemCase.setTransformOriginPoint( self.m_originalAdiCtr )
        self.m_scene.addItem (self.m_itemCase)

        self.centerOn (self.width()/2, self.height()/2)

        self.updateView()
Ejemplo n.º 31
0
    def set_rect_bars(self):
        global now
        if self.input_rect:
            if now != None:
                buf = self.scene.itemAt(now, QTransform()).rect()
                self.rect = [buf.left(), buf.top(), buf.right(), buf.bottom()]

            self.input_rect = False
            self.adding_lines_btn.setDisabled(False)
            self.clear_btn.setDisabled(False)
            self.cut_btn.setDisabled(False)
        else:
            self.pen.setColor(self.color_out_rect)
            now = None
            self.rect = None
            self.input_rect = True
            self.adding_lines_btn.setDisabled(True)
            self.clear_btn.setDisabled(True)
            self.cut_btn.setDisabled(True)
Ejemplo n.º 32
0
    def rotateImage90(self):
        """
        Rotate image 90º clockwise
        """
        if self.image.isNull() == False:
            transform90 = QTransform().rotate(90)
            pixmap = QPixmap(self.image)

            rotated = pixmap.transformed(transform90,
                                         mode=Qt.SmoothTransformation)

            self.image_label.setPixmap(
                rotated.scaled(self.image_label.size(), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            self.image = QPixmap(rotated)
            self.image_label.repaint()  # repaint the child widget
        else:
            # No image to rotate
            pass
Ejemplo n.º 33
0
 def initUI(self):
     self.setWindowTitle(self.title)
     self.setGeometry(self.left, self.top, self.width, self.height)
     ##Buttons
     buttonRec = QPushButton('Record new movement', self)
     buttonRec.setToolTip(
         'Start the recording of a new movement, do it multiple times to build the database'
     )
     buttonRec.move(20, 560)
     buttonRec.resize(150, 30)
     buttonRec.clicked.connect(self.startRec)
     buttonStopRec = QPushButton('Stop recording', self)
     buttonStopRec.setToolTip('Stop the recording of the new movement')
     buttonStopRec.move(220, 560)
     buttonStopRec.clicked.connect(self.stopRec)
     buttonMakeFile = QPushButton('Save to file', self)
     buttonMakeFile.setToolTip(
         'Save all the recorded movements to the dataset.csv file')
     buttonMakeFile.move(420, 560)
     buttonMakeFile.clicked.connect(self.makeFile)
     ##Captors
     self.captors = [150, 0, 450, 0, 625, 250, 450, 520, 150, 520, 0, 250]
     self.rotation = [0, 0, 90, 180, 180, 270]
     captors = []
     for i in range(0, 6):
         captor = QLabel(self)
         img = QPixmap('ir-detector-small.png')
         transform = QTransform().rotate(self.rotation[i])
         img = img.transformed(transform, Qt.SmoothTransformation)
         captor.setPixmap(img)
         captor.move(self.captors[i * 2] - 5, self.captors[i * 2 + 1] - 5)
         captors.append(captor)
     self.circles = [100, 400, 150, 230, 200, 300, 480, 300, 226]
     self.circlesInitPos = self.circles.copy()
     ##Timer
     self.sampleTimer = QTimer()
     self.sampleTimer.timeout.connect(self.sample)
     self.updateTimer = QTimer()
     self.updateTimer.timeout.connect(self.paintUpdate)
     self.updateTimer.start(int(1000 / self.FPS))
     self.countTimer = QTimer()
     self.countTimer.timeout.connect(self.timerRec)
     self.show()
Ejemplo n.º 34
0
    def _validateImage(self):
        if (self._sharedImage.transform != DemoItem._transform and
                not Colors.noRescale) or (self._sharedImage.image is None and
                                          self._sharedImage.pixmap is None):
            # (Re)create image according to new transform.
            self._sharedImage.image = None
            self._sharedImage.pixmap = None
            self._sharedImage.transform = DemoItem._transform

            # Let subclass create and draw a new image according to the new
            # transform.
            if Colors.noRescale:
                transform = QTransform()
            else:
                transform = DemoItem._transform
            image = self.createImage(transform)
            if image is not None:
                if Colors.showBoundingRect:
                    # Draw red transparent rect.
                    painter = QPainter(image)
                    painter.fillRect(image.rect(), QColor(255, 0, 0, 50))
                    painter.end()

                self._sharedImage.unscaledBoundingRect = self._sharedImage.transform.inverted(
                )[0].mapRect(QRectF(image.rect()))

                if Colors.usePixmaps:
                    if image.isNull():
                        self._sharedImage.pixmap = QPixmap(1, 1)
                    else:
                        self._sharedImage.pixmap = QPixmap(image.size())

                    self._sharedImage.pixmap.fill(QColor(0, 0, 0, 0))
                    painter = QPainter(self._sharedImage.pixmap)
                    painter.drawImage(0, 0, image)
                else:
                    self._sharedImage.image = image

                return True
            else:
                return False

        return True
Ejemplo n.º 35
0
    def contextMenuEvent(self, event):

        item = self.itemAt(event.scenePos(), QTransform())

        if item != None and item != self.pixmapItem and type(
                item) is RectangleLabelItem:
            #Later do something to remove rectangles
            menu = item.contextMenu()
            menu.addSeparator()
            menu.addAction("Remove rectangle",
                           lambda: self.removeLabelItem(item))

            menu.exec(event.screenPos())
            return

        menu = QMenu()
        menu.addAction("Insert bounding rectangle",
                       lambda: self.insertBoundingRectangle(event.scenePos()))
        menu.exec(event.screenPos())
Ejemplo n.º 36
0
    def dataTransform(self):
        """Return the transform that maps from this image's input array to its
        local coordinate system.

        This transform corrects for the transposition that occurs when image data
        is interpreted in row-major order.
        """
        # Might eventually need to account for downsampling / clipping here
        tr = QTransform()
        if self.axisOrder == 'row-major':
            # transpose
            tr.scale(1, -1)
            tr.rotate(-90)
        return tr
Ejemplo n.º 37
0
    def draw(self, page, painter, key, tile, paperColor=None):
        """Draw a tile on the painter.

        The painter is already at the right position and rotation.
        For the Poppler page and renderer, draw() is only used for printing.
        (See AbstractPage.print().)

        """
        source = self.map(key, page.pageRect()).mapRect(
            QRectF(*tile)).toRect()  # rounded
        target = QRectF(0, 0, tile.w, tile.h)
        if key.rotation & 1:
            target.setSize(target.size().transposed())

        doc = page.document
        p = doc.page(page.pageNumber)

        with self.setup(doc, self.printRenderBackend, paperColor):
            if self.printRenderBackend == popplerqt5.Poppler.Document.ArthurBackend:
                # Poppler's Arthur backend removes the current transform from
                # the painter (it sets a default CTM, instead of combining it
                # with the current transform). We let Poppler draw on a QPicture,
                # and draw that on our painter.
                pic = QPicture()
                p.renderToPainter(QPainter(pic), page.dpi, page.dpi,
                                  source.x(), source.y(), source.width(),
                                  source.height())
                # our resolution could be different, scale accordingly
                painter.save()
                painter.scale(
                    pic.logicalDpiX() / painter.device().logicalDpiX(),
                    pic.logicalDpiY() / painter.device().logicalDpiY())
                pic.play(painter)
                painter.restore()
            else:
                # Make an image exactly in the printer's resolution
                m = painter.transform()
                r = m.mapRect(source)  # see where the source ends up
                w, h = r.width(), r.height()
                if m.m11() == 0:
                    w, h = h, w  # swap if rotation & 1  :-)
                # now we know the scale from our dpi to the paintdevice's logicalDpi!
                hscale = w / source.width()
                vscale = h / source.height()
                s = QTransform().scale(hscale, vscale).mapRect(source)
                dpiX = page.dpi * hscale
                dpiY = page.dpi * vscale
                img = p.renderToImage(dpiX, dpiY, s.x(), s.y(), s.width(),
                                      s.height())
                painter.drawImage(target, img, QRectF(img.rect()))
Ejemplo n.º 38
0
    def init (self):
        self.m_scaleX = self.width() / self.m_originalWidth
        self.m_scaleY = self.height() / self.m_originalHeight


        self.m_itemFace_1 = QGraphicsSvgItem(":/qfi/images/alt/alt_face_1.svg")
        self.m_itemFace_1.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemFace_1.setZValue( self.m_face1Z )
        self.m_itemFace_1.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemFace_1.setTransformOriginPoint( self.m_originalAltCtr )
        self.m_scene.addItem (self.m_itemFace_1)

        self.m_itemFace_2 = QGraphicsSvgItem(":/qfi/images/alt/alt_face_2.svg")
        self.m_itemFace_2.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemFace_2.setZValue( self.m_face2Z )
        self.m_itemFace_2.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemFace_2.setTransformOriginPoint( self.m_originalAltCtr )
        self.m_scene.addItem (self.m_itemFace_2)

        self.m_itemFace_3 = QGraphicsSvgItem(":/qfi/images/alt/alt_face_3.svg")
        self.m_itemFace_3.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemFace_3.setZValue( self.m_face3Z )
        self.m_itemFace_3.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemFace_3.setTransformOriginPoint( self.m_originalAltCtr )
        self.m_scene.addItem (self.m_itemFace_3)

        self.m_itemHand_1 = QGraphicsSvgItem(":/qfi/images/alt/alt_hand_1.svg")
        self.m_itemHand_1.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemHand_1.setZValue( self.m_hand1Z )
        self.m_itemHand_1.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemHand_1.setTransformOriginPoint( self.m_originalAltCtr )
        self.m_scene.addItem (self.m_itemHand_1)

        self.m_itemHand_2 = QGraphicsSvgItem(":/qfi/images/alt/alt_hand_2.svg")
        self.m_itemHand_2.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemHand_2.setZValue( self.m_hand2Z )
        self.m_itemHand_2.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemHand_2.setTransformOriginPoint( self.m_originalAltCtr )
        self.m_scene.addItem (self.m_itemHand_2)

        self.m_itemCase = QGraphicsSvgItem(":/qfi/images/alt/alt_case.svg")
        self.m_itemCase.setCacheMode (QGraphicsItem.NoCache)
        self.m_itemCase.setZValue( self.m_caseZ )
        self.m_itemCase.setTransform( QTransform.fromScale( self.m_scaleX, self.m_scaleY ), True )
        self.m_itemCase.setTransformOriginPoint( self.m_originalAltCtr )
        self.m_scene.addItem (self.m_itemCase)

        self.centerOn (self.width()/2, self.height()/2)

        self.updateView()
Ejemplo n.º 39
0
    def move_unit(self):
        game_field = self.parent()
        if not self.animation.timer.isActive():
            if not self.death_animation.timer.isActive():
                self.clear()
                self.pacman.init_start_state()
                self.animation.timer.start(70)
        else:
            if self.pacman.is_dead:
                game_field.game.blinky.init_start_state()
                game_field.game.pinky.init_start_state()
                game_field.game.inky.init_start_state()
                game_field.game.clyde.init_start_state()

                self.animation.timer.stop()
                self.death_animation.timer.start(70)
                self.clear()

                if self.pacman.lifes < 0:
                    game_field.show_game_over_dialog()

            else:
                if Game.is_level_complete:
                    if game_field.game.level + 1 > 3:
                        game_field.game.level = 1
                    else:
                        game_field.game.level += 1
                    game_field.game.restart()
                    game_field.scene.clear()
                    game_field.init_map()
                    game_field.scene.update()
                self.pacman.move()
                x_pos = self.pacman.x * self.width()
                y_pos = self.pacman.y * self.height()
                pacman_direction = self.pacman.current_direction
                self.animation.current_direction = pacman_direction
                self.move(x_pos, y_pos)

                scene = self.parentWidget().scene
                food = scene.itemAt(x_pos, y_pos, QTransform())
                if food is not None:
                    scene.removeItem(food)
Ejemplo n.º 40
0
    def __init__(self, x, y, rotation, i, scene: QGraphicsScene, rocket_id):
        super().__init__()
        self.rocket_id = rocket_id.__int__()
        number_of_active_bullets = 0
        if self.rocket_id == 1:
            number_of_active_bullets = Server.rocket1_bulletsCounter
        elif self.rocket_id == 2:
            number_of_active_bullets = Server.rocket2_bulletsCounter

        if number_of_active_bullets < Server.maximum_of_bullets:
            self.image = QPixmap("Images/bullet.png")
            t = QTransform().rotate(rotation)
            self.setStyleSheet("background:transparent;color:white;")
            self.image = self.image.transformed(t)
            self.setPixmap(self.image)
            self.init_x = x + 20 + 30 * float(cos(radians(rotation)))
            self.init_y = y + 20 - 30 * float(sin(radians(rotation)))
            self.IDS = Server.bulletIDS
            Server.bulletIDS = Server.bulletIDS + 1
            inttX = int(round(self.init_x))
            inttY = int(round(self.init_y))
            if self.rocket_id == 1:# u odnosu na to koja raketa je ispalila metak svrstaj ga u odredjen kolekciju
                Server.bulletsCollection1X[self.IDS] = 0
                Server.bulletsCollection1Y[self.IDS] = 0
                Server.bulletsCollection1X[self.IDS] = inttX
                Server.bulletsCollection1Y[self.IDS] = inttY
            elif self.rocket_id == 2:
                Server.bulletsCollection2X[self.IDS] = 0
                Server.bulletsCollection2Y[self.IDS] = 0
                Server.bulletsCollection2X[self.IDS] = inttX
                Server.bulletsCollection2Y[self.IDS] = inttY

            self.scene = scene
            self.xMovement = float(cos(radians(rotation)))
            self.yMovement = float(sin(radians(rotation)))
            scene.addWidget(self)
            self.kreni.connect(self.moveSelf)
            self.initBullet()
            if self.rocket_id == 1:
                Server.rocket1_bulletsCounter = Server.rocket1_bulletsCounter + 1
            elif self.rocket_id == 2:
                Server.rocket2_bulletsCounter = Server.rocket2_bulletsCounter + 1
Ejemplo n.º 41
0
    def mousePressEvent(self, event):
        self.rb_selected_points.clear()

        cursor_pos = event.scenePos().toPoint()
        item_under_cursor = self.itemAt(cursor_pos, QTransform())

        if item_under_cursor is not None:
            if self.highlighted_item is not None and \
                    not self.highlighted_item.isHighlighted() and \
                    not self.highlighted_item.isPersistent():
                self.highlighted_item.unhighlight_self()
            if self.selected_item is not None and \
                    not self.selected_item.isHighlighted() and \
                    not self.selected_item.isPersistent():
                self.selected_item.unhighlight_self()

            self.selected_item = item_under_cursor
            self.selected_item.mousePressEvent(event)
            if not self.parent.main_window.MODE_RECOLOR_NODE:
                self.highlighted_item = item_under_cursor
                self.highlighted_item.highlight_self()
            self._move = True
        else:
            # Clicking else where resets any selection previously made
            if self.highlighted_item is not None:
                if not self.highlighted_item.isHighlighted(
                ) and not self.highlighted_item.isPersistent():
                    self.highlighted_item.unhighlight_self()
            if self.selected_item is not None:
                if not self.selected_item.isHighlighted(
                ) and not self.selected_item.isPersistent():
                    self.selected_item.unhighlight_self()
            self.highlighted_item = None
            self.selected_item = None

            if self.parent.main_window.MODE_RUBBER_BAND:
                # Initializing rubber band
                self.rb_origin = self.parent.mapFromScene(cursor_pos)
                self.rubber_band = QRubberBand(QRubberBand.Rectangle,
                                               self.parent)
                self.rubber_band.setGeometry(QRect(self.rb_origin, QSize()))
                self.rubber_band.show()
Ejemplo n.º 42
0
    def __placeShip(self, shipListItem, x, y, rotation):
        sceneX, sceneY = (x + 1) * self.tileSize, (y + 1) * self.tileSize

        shipListItem.count -= 1
        shipListItem.counterText.setPlainText(str(shipListItem.count))

        pixmap = QPixmap(shipListItem.image).transformed(QTransform().rotate(
            (rotation.value)))
        placedShip = QGraphicsPixmapItem(pixmap)
        placedShip.setData(0, rotation)
        placedShip.setData(1, shipListItem)
        placedShip.setData(2, QPoint(x, y))  # position in map coordinates

        placedShip.setPos(sceneX, sceneY)
        placedShip.setTransformationMode(
            Qt.TransformationMode.SmoothTransformation)
        placedShip.setScale(self.__scaleFactor)

        self.__placedShips.append(placedShip)
        self.__scene.addItem(placedShip)
Ejemplo n.º 43
0
 def paint(self, painter):
     if self._rubberBandRect is None:
         return
     widget = self.parent()
     # okay, OS-native rubber band does not support painting with
     # floating-point coordinates
     # paint directly on the widget with unscaled context
     widgetOrigin = widget.mapToWidget(self._rubberBandRect.bottomLeft())
     widgetMove = widget.mapToWidget(self._rubberBandRect.topRight())
     option = QStyleOptionRubberBand()
     option.initFrom(widget)
     option.opaque = False
     option.rect = QRectF(widgetOrigin, widgetMove).toRect()
     option.shape = QRubberBand.Rectangle
     painter.save()
     painter.setRenderHint(QPainter.Antialiasing, False)
     painter.setTransform(QTransform())
     widget.style().drawControl(QStyle.CE_RubberBand, option, painter,
                                widget)
     painter.restore()
Ejemplo n.º 44
0
    def actualizar_imagen_enemigos(self, MyPlayerEvent):
        if self.started:
            pl = MyPlayerEvent.player
            d = pl.daño
            r = pl.rotacion
            tipo = pl.tipo
            label = pl.image
            if pl.is_dead:
                c = pl.contador_dead % 6
                pixmap = QPixmap(entidad_muerta[tipo][c])
            else:
                c = pl.contador_game % 40 // 10 + 1
                pixmap = QPixmap(all_sprites_shits[tipo][d][c])

            pixmap = pixmap.scaled(self.w / 70 * pl.tamaño**0.8, 
                                   self.w / 70 * pl.tamaño**0.8)
            transform = QTransform().rotate(pl.angulo - r)
            pixmap = pixmap.transformed(transform, Qt.SmoothTransformation)
            label.move(pl.position[0], pl.position[1])
            label.setPixmap(pixmap)
Ejemplo n.º 45
0
def drawGlyphImage(painter, glyph, scale, drawSelection=True, selectionColor=None):
    image = glyph.image
    pixmap = image.getRepresentation("defconQt.QPixmap")
    if pixmap is None:
        return
    if selectionColor is None:
        selectionColor = defaultColor("glyphSelection")
    painter.save()
    painter.setTransform(QTransform(*image.transformation), True)
    painter.save()
    painter.translate(0, pixmap.height())
    painter.scale(1, -1)
    painter.drawPixmap(0, 0, pixmap)
    painter.restore()
    if drawSelection and image.selected:
        pen = QPen(selectionColor)
        pen.setWidthF(3.5 * scale)
        painter.setPen(pen)
        painter.drawRect(pixmap.rect())
    painter.restore()
Ejemplo n.º 46
0
    def change_img(self, nro_img, iden, carpeta, angle, tipo_img):
        obj = getattr(self, 'img_' + iden)
        path = 'IMGS/{}/{}{}.png'.format(carpeta, tipo_img, nro_img)
        if path not in self.imagenes:
            img = QPixmap(path)
            img = img.scaled(obj.tamano, obj.tamano, Qt.KeepAspectRatio)
            self.imagenes[path] = img
        else:
            img = self.imagenes[path]

        angle = round(360 - angle)
        key = path + str(angle)
        if key not in self.imagenes:
            img = img.transformed(QTransform().rotate(angle),
                                  Qt.SmoothTransformation)
            self.imagenes[key] = img
        else:
            img = self.imagenes[key]

        obj.setPixmap(img)
Ejemplo n.º 47
0
    def __init__(self):
        super().__init__()

        self.language = settings.LANG
        self.csv_separator = settings.CSV_SEPARATOR
        self.fmt_float = settings.FMT_FLOAT

        self.nodes = {}
        self.nb_nodes = 0
        self.adj_list = {}
        self.current_line = None
        self.current_port = None
        self.project_path = ''

        self.setSceneRect(
            QRectF(0, 0, settings.SCENE_SIZE[0], settings.SCENE_SIZE[1]))
        self.transform = QTransform()
        self.selectionChanged.connect(self.selection_changed)

        self._init_with_default_node()
Ejemplo n.º 48
0
    def __init__(self, letter, scene, lliw="black"):

        self.image = QPixmap.fromImage(self.set_tile(letter, lliw))
        super(Tile, self).__init__(self.image)

        self.letter = letter
        self.colour = lliw
        self.scene = scene

        self.pixmap_item.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable)
        self.pixmap_item.setTransform(QTransform())
        self.pixmap_item.setAcceptedMouseButtons(Qt.LeftButton)
        self.pixmap_item.setZValue(1000)
        self.pixmap_item.tile = self
        self.pixmap_item.hide()
        self.scene.addItem(self.pixmap_item)

        self.cell = None
        self.fade = None
        self.movable(False)
Ejemplo n.º 49
0
    def __init__(self,
                 mark_item: MarkItem,
                 scene,
                 view_scale,
                 transform=QTransform(),
                 parent=None):
        super(OutlineItem, self).__init__(scene=scene,
                                          shape=None,
                                          view_scale=view_scale,
                                          transform=transform,
                                          parent=parent)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)

        self._is_browser_result = False
        self._pen.setColor(mark_item.color)
        self._mark_item = mark_item
        self._mark_item.visible_changed.connect(self.visible_changed)
        self._mark_item.fill_changed.connect(self.update)
        self._mark_item.mark_item_color_changed.connect(self.update)
        self.setSelected(True)
        self._selected = False
Ejemplo n.º 50
0
 def __init__(self, position, scene, style=Qt.SolidLine,brush=Qt.cyan,
              rect=None, matrix=QTransform()):
     super(BoxItem, self).__init__()
     self.setFlags(QGraphicsItem.ItemIsSelectable|
                   QGraphicsItem.ItemIsMovable|
                   QGraphicsItem.ItemIsFocusable)
     if rect is None:
         PointSize = scene.views()[0].PointSize
         rect = QRectF(-10 * PointSize, -PointSize, 20 * PointSize,
                       2 * PointSize)
     self.rect = rect
     self.style = style
     self.brush = brush
     self.setPos(position)
     self.setTransform(matrix)
     scene.clearSelection()
     scene.addItem(self)
     self.setSelected(True)
     self.setFocus()
     global Dirty
     Dirty = True
Ejemplo n.º 51
0
    def wheelEvent(self, wheel_event):
        if wheel_event.modifiers() == Qt.NoModifier:
            try:
                delta = wheel_event.angleDelta().y()
            except AttributeError:
                delta = wheel_event.delta()
            delta = max(min(delta, 480), -480)
            mouse_before_scale_in_scene = self.mapToScene(wheel_event.pos())

            scale_factor = 1 + (0.2 * (delta / 120.0))
            scaling = QTransform(scale_factor, 0, 0, scale_factor, 0, 0)
            self.setTransform(self.transform() * scaling)

            mouse_after_scale_in_scene = self.mapToScene(wheel_event.pos())
            center_in_scene = self.mapToScene(self.frameRect().center())
            self.centerOn(center_in_scene + mouse_before_scale_in_scene -
                          mouse_after_scale_in_scene)

            wheel_event.accept()
        else:
            QGraphicsView.wheelEvent(self, wheel_event)
Ejemplo n.º 52
0
    def __init__(self, midiNumber, dur, acc, tieToPrev, vertPosLookUp,
                 extraLines, svgFolder, lineDistance, invert, horPos, vertPos,
                 addBarLine, head, appctxt, parent):
        if dur < 16:
            filePath = appctxt.get_resource(str(svgFolder / "stem.svg"))
            widthRel = 1 / 5
            heightRel = 3.5
            horOff = head.widthRel - 1 / 5
            vertOff = -heightRel + 1 / 2
        else:
            filePath = None

        if filePath is not None:
            super(Stem, self).__init__(filePath, parent)
        else:
            super(Stem, self).__init__()
        self.isNone = True if filePath is None else False
        if self.isNone is False:
            #self.rect = QRectF(0, 0, self.widthReal, self.heightReal)
            self.widthRel = widthRel
            self.heightRel = heightRel  # na to ypologisw akrivws
            self.lineDistance = lineDistance
            self.dur = dur
            self.heightBefore = self.boundingRect().height()
            self.widthBefore = self.boundingRect().width()
            self.widthScale = self.widthRel * self.lineDistance / self.widthBefore
            self.heightScale = self.heightRel * self.lineDistance / self.heightBefore
            self.widthReal = self.widthRel * self.lineDistance
            self.heightReal = self.heightRel * self.lineDistance
            if invert == 1:
                self.setTransform(
                    QTransform(-1, 0, 0, -1, self.widthReal, self.heightReal))
            self.scale(self.widthScale, self.heightScale)
            #print(f"{horPos} {vertPos}")
            # self.setPos(horPos + self.lineDistance - self.widthReal, vertPos - self.heightReal + self.lineDistance/2) #
            ########self.setPos(horPos, vertPos + self.lineDistance/2)
            #print(f" before {self.heightBefore} real {self.heightReal} vertPos {vertPos}")
            self.setPos(horPos + self.lineDistance * horOff,
                        vertPos + self.lineDistance * vertOff)
            self.rightMostPoint = horPos + horOff * self.lineDistance + self.widthReal
Ejemplo n.º 53
0
def transform_factory(
    horizontal_scaling_factor: float = 1.,
    vertical_shearing_factor: float = .0,
    horizontal_projection_factor: float = .0,
    horizontal_shearing_factor: float = .0,
    vertical_scaling_factor: float = 1.,
    vertical_projection_factor: float = 0.,
    horizontal_translation_factor: float = 0.,
    vertical_translation_factor: float = 0.,
    division_factor: float = 1.0,
) -> QTransform:
    return QTransform(
        horizontal_scaling_factor,
        vertical_shearing_factor,
        horizontal_projection_factor,
        horizontal_shearing_factor,
        vertical_scaling_factor,
        vertical_projection_factor,
        horizontal_translation_factor,
        vertical_translation_factor,
        division_factor,
    )
Ejemplo n.º 54
0
    def setIcon(self, widget, ico, rotate=0):
        if isinstance(ico, str):
            icon = QIcon()
            if app_defs.APP_IMAGE_DIR:
                path = app_defs.APP_IMAGE_DIR
            else:
                path = 'img'

            path = os.path.join(path, ico)
            if not os.path.isfile(path):
                logging.warning(f'File {path} does not exist or is not a file')

            pixmap = QPixmap(path)
            if rotate:
                transf = QTransform().rotate(rotate)
                pixmap = QPixmap(pixmap.transformed(transf))

            icon.addPixmap(pixmap)
        else:
            icon = self.style().standardIcon(ico)

        widget.setIcon(icon)
Ejemplo n.º 55
0
    def mousePressEvent(self, event):
        QGraphicsScene.mousePressEvent(self, event)

        if self.piano.contains(event.scenePos()):
            item = self.itemAt(event.scenePos(), QTransform())
            if isinstance(item, PianoKeyItem) and item.note is not None:
                self.last_piano_note = item.note
                self.noteclicked.emit(self.last_piano_note, True)
                return

        if not (any(key.pressed for key in self.piano_keys)
                or any(note.pressed for note in self.notes)):
            for note in self.selected_notes:
                note.setSelected(False)
            self.selected_notes = []

            if event.button() == Qt.LeftButton:
                if self.insert_mode:
                    self.place_ghost = True
                else:
                    self.marquee_select = True
                    self.marquee_rect = QRectF(event.scenePos().x(),
                                               event.scenePos().y(), 1, 1)
                    self.marquee = QGraphicsRectItem(self.marquee_rect)
                    self.marquee.setBrush(QColor(255, 255, 255, 100))
                    self.addItem(self.marquee)

        else:
            for s_note in self.notes:
                if s_note.pressed and s_note in self.selected_notes:
                    break
                elif s_note.pressed and s_note not in self.selected_notes:
                    for note in self.selected_notes:
                        note.setSelected(False)
                    self.selected_notes = [s_note]
                    break
            for note in self.selected_notes:
                if not self.velocity_mode:
                    note.mousePressEvent(event)
Ejemplo n.º 56
0
def compute_SMBR(geom):
    area = float("inf")
    angle = 0
    width = float("inf")
    height = float("inf")
    if (geom is None):
        return QgsGeometry()
    hull = geom.convexHull()
    if (hull.isEmpty()):
        return QgsGeometry()
    x = hull.asPolygon()
    vertexId = 0
    pt0 = x[0][vertexId]
    pt1 = pt0
    prevAngle = 0.0
    size = len(x[0])
    for vertexId in range(0, size - 0):
        pt2 = x[0][vertexId]
        currentAngle = lineAngle(pt1.x(), pt1.y(), pt2.x(), pt2.y())
        rotateAngle = 180.0 / math.pi * (currentAngle - prevAngle)
        prevAngle = currentAngle
        t = QTransform.fromTranslate(pt0.x(), pt0.y())
        t.rotate(rotateAngle)
        t.translate(-pt0.x(), -pt0.y())
        hull.transform(t)
        bounds = hull.boundingBox()
        currentArea = bounds.width() * bounds.height()
        if (currentArea < area):
            minRect = bounds
            area = currentArea
            angle = 180.0 / math.pi * currentAngle
            width = bounds.width()
            height = bounds.height()
        pt2 = pt1
    minBounds = QgsGeometry.fromRect(minRect)
    minBounds.rotate(angle, QgsPointXY(pt0.x(), pt0.y()))
    if (angle > 180.0):
        angle = math.fmod(angle, 180.0)
    return minBounds, area, angle, width, height
Ejemplo n.º 57
0
    def __init__(self, **kwargs):
        QGraphicsView.__init__(self, **kwargs)
        self.setRenderHints(QPainter.Antialiasing)
        self.setBackgroundBrush(QBrush(QColor(Qt.cyan).lighter(150)))
        #self.setBackgroundBrush( QBrush( QColor(Qt.darkGray).darker(200) ) )
        # invert y axis because scene coordinates system is direct,
        # with y up oriented
        self.setTransform(QTransform.fromScale(1.0, -1.0))
        # viewport control (part of the scene displayed)
        self.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        # seems that the translate stuff is a bit buggy in Qt
        # https://bugreports.qt-project.org/browse/QTBUG-7328
        # this does not help
        #self.setAlignment(Qt.Alignment(0))

        # AnchorUnderMouse works by moving the wiewport around with scrollbars
        # so movable scrollbars are needed,
        # and the scenerect should be large enough
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
Ejemplo n.º 58
0
 def wheelEvent(self, event):
     #print("WHEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEL")
     #print(event.angleDelta())
     #print(event.pixelDelta().isNull())
     if self.ctrlPressed: 
         if event.angleDelta().y() > 0:
             #print("GIATIDENZOUMAREISSSSSSSSSSSSS")
             self.currentZoomFactor += 0.1
         else:
             self.currentZoomFactor -= 0.1
         self.currentZoomFactor = max(self.minZoomFactor, min(self.currentZoomFactor, self.maxZoomFactor))
         #self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)#self.AnchorUnderMouse)
         #print(self.currentZoomFactor)
         self.setTransform(QTransform(self.currentZoomFactor, 0.0, 0.0, self.currentZoomFactor, 0, 0))
         
 #        print(self.mapToScene(self.viewport().geometry()).boundingRect())
     else: 
         deltaX = event.angleDelta().x()
         self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() + deltaX/2)
         deltaY = event.angleDelta().y()
         self.verticalScrollBar().setValue(self.verticalScrollBar().value() + deltaY/2)
     self.updatePaintersRectSignal.emit(self.currentZoomFactor)
Ejemplo n.º 59
0
 def OnWindowResize(self, event):
     Timer(0.1, self.FixOverlays).start()
     Timer(0.2, self.DrawFixedScale).start()
     if self.camOpen and not self.capTimer.isActive():
         pix = QPixmap(self.camView.width(), self.camView.height())
         pix.fill(Qt.black)
         img = self.img.scaled(self.camView.size(), Qt.KeepAspectRatio)
         painter = QPainter(pix)
         painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform, True)
         pointx = int(np.round(np.fabs(self.camView.width() - img.width())/2))
         pointy = int(np.round(np.fabs(self.camView.height() - img.height())/2))
         painter.drawImage(pointx, pointy, img)
         painter.end()
         fh = 1
         fv = 1
         if self.fliphCheck.isChecked():
             fh = -1
         if self.flipvCheck.isChecked():
             fv = -1
         if(fv != 1 or fh != 1):
             pix = pix.transformed(QTransform().scale(fh, fv))
         self.camView.setPixmap(pix)
Ejemplo n.º 60
0
    def show_pushka(self):
        # показ инструкции

        self.podskaz = QLabel('', self)
        self.podskaz.setGeometry(1200, 200, 200, 100)
        self.podskaz.setText(
            'W - Поднять пушку,\nS - Опустить пушку,\nSpace - Выстрел ')
        self.podskaz.show()

        # показ пушки

        self.angel = -45
        self.pic = QLabel(self)
        self.pixmap = QPixmap('pushka.png')
        t = QTransform().rotate(self.angel)
        self.pic.setPixmap(self.pixmap.transformed(t))

        self.vse = {
            -45: (5, self.sdvig_y - 187),
            -5: (5, self.sdvig_y - 133),
            -10: (6, self.sdvig_y - 139),
            -15: (6, self.sdvig_y - 148),
            -30: (4, self.sdvig_y - 167),
            -35: (5, self.sdvig_y - 173),
            -20: (5, self.sdvig_y - 155),
            -25: (5, self.sdvig_y - 160),
            -40: (5, self.sdvig_y - 182),
            -50: (6, self.sdvig_y - 191),
            -55: (7, self.sdvig_y - 200),
            -60: (8, self.sdvig_y - 205),
            -65: (11, self.sdvig_y - 210),
            -70: (14, self.sdvig_y - 214),
            -75: (18, self.sdvig_y - 217),
            -80: (20, self.sdvig_y - 220),
            -85: (24, self.sdvig_y - 223)
        }

        self.pic.move(5, self.sdvig_y - 186)
        self.pic.show()