Exemplo n.º 1
0
    def reload(self):
        self._reset_scene()
        self._arrows.clear()
        self.disasm = self.workspace.instance.project.analyses.Disassembly(
            function=self._function_graph.function)
        self.workspace.view_manager.first_view_in_category(
            'console').push_namespace({
                'disasm': self.disasm,
            })

        self.blocks.clear()
        self._insaddr_to_block.clear()

        supergraph = self._function_graph.supergraph
        for n in supergraph.nodes():
            block = QGraphBlock(self.workspace,
                                self._function_graph.function.addr,
                                self.disasm_view, self.disasm, self.infodock,
                                n.addr, n.cfg_nodes, get_out_branches(n))
            if n.addr == self._function_graph.function.addr:
                self.entry_block = block
            self.scene().addItem(block)
            self.blocks.append(block)

            for insn_addr in block.addr_to_insns.keys():
                self._insaddr_to_block[insn_addr] = block

        self.request_relayout()
        # Leave some margins
        scene = self.scene()
        rect = scene.itemsBoundingRect()  # type: QRectF
        scene.setSceneRect(
            QRectF(rect.x() - 200,
                   rect.y() - 200,
                   rect.width() + 400,
                   rect.height() + 400))

        # determine initial view focus point
        self._reset_view()

        # show the graph
        self.show()
Exemplo n.º 2
0
    def zoom(self, p_abs, p_mapped, angle):
        by = 0
        velocity = 2 * (1 / self.current_scale) + 0.5
        if velocity > 3:
            velocity = 3

        direction = ''
        if angle > 0:
            by = 1 + (angle / 360 * 0.1 * velocity)
            direction = 'in'
        elif angle < 0:
            by = 1 - (-angle / 360 * 0.1 * velocity)
            direction = 'out'
        else:
            by = 1

        scene_rect_width = self.mapFromScene(self.sceneRect()).boundingRect().width()
        scene_rect_height = self.mapFromScene(self.sceneRect()).boundingRect().height()

        if direction == 'in':
            if self.current_scale * by < 3:
                self.scale(by, by)
                self.current_scale *= by
        elif direction == 'out':
            if scene_rect_width * by >= self.viewport().size().width() and scene_rect_height * by >= self.viewport().size().height():
                self.scale(by, by)
                self.current_scale *= by

        w = self.viewport().width()
        h = self.viewport().height()
        wf = self.mapToScene(QPoint(w - 1, 0)).x() - self.mapToScene(QPoint(0, 0)).x()
        hf = self.mapToScene(QPoint(0, h - 1)).y() - self.mapToScene(QPoint(0, 0)).y()
        lf = p_mapped.x() - p_abs.x() * wf / w
        tf = p_mapped.y() - p_abs.y() * hf / h

        self.ensureVisible(lf, tf, wf, hf, 0, 0)

        target_rect = QRectF(QPointF(lf, tf),
                             QSizeF(wf, hf))
        self.total_scale_div = target_rect.width() / self.viewport().width()

        self.ensureVisible(target_rect, 0, 0)
Exemplo n.º 3
0
    def _boundingRect(self):
        height, width = 0, 0

        width += self._addr_width
        width += self.LINEAR_INSTRUCTION_OFFSET

        if self._bytes_text:
            height += Conf.disasm_font_height * len(
                self._bytes_text) * self.currentDevicePixelRatioF()
        else:
            height += Conf.disasm_font_height * self.currentDevicePixelRatioF()

        if self._bytes_text:
            width += max(
                len(line) for line in self._bytes_text
            ) * Conf.disasm_font_width * self.currentDevicePixelRatioF()
        else:
            width += Conf.disasm_font_metrics.width(
                QUnknownBlock.DEFAULT_TEXT) * self.currentDevicePixelRatioF()
        return QRectF(0, 0, width, height)
    def boundingRect(self):
        """
		This pure virtual function defines the outer bounds of the item as a rectangle.

		:return: create the bounding of the item
		:rtype: QRectF
		"""
        if self._boundingRect:
            return self._boundingRect

        srcPos = self.scene().getGraphics(
            self._dataVB.getSrcComponent()).scenePos()
        dstPos = self.scene().getGraphics(
            self._dataVB.getDestComponent()).scenePos()

        leftCornerX = min(srcPos.x(), dstPos.x())
        leftCornerY = min(srcPos.y(), dstPos.y())
        width = abs(srcPos.x() - dstPos.x())
        height = abs(srcPos.y() - dstPos.y())
        return QRectF(leftCornerX, leftCornerY, width, height)
Exemplo n.º 5
0
 def setImage(self, image):
     """ Set the scene's current image pixmap to the input QImage or QPixmap.
     Raises a RuntimeError if the input image has type other than QImage or QPixmap.
     :type image: QImage | QPixmap
     """
     if type(image) is QPixmap:
         pixmap = image
     elif type(image) is QImage:
         pixmap = QPixmap.fromImage(image)
     else:
         raise RuntimeError(
             "ImageViewer.setImage: Argument must be a QImage or QPixmap."
         )
     if self.hasImage():
         self._pixmapHandle.setPixmap(pixmap)
     else:
         self._pixmapHandle = self.scene.addPixmap(pixmap)
     self.setSceneRect(QRectF(
         pixmap.rect()))  # Set scene size to image size.
     self.updateViewer()
Exemplo n.º 6
0
    def __init__(self, width, height):
        super(TMSTester, self).__init__(None)

        self.setStyleSheet("background: transparent")

        self.canvasSize = QRectF(QPointF(0, 0), QPointF(width, height))

        self.view = QGraphicsView()
        self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.scene = QGraphicsScene(0, 0, width, height, self.view)
        self.view.setScene(self.scene)

        self.centreCoordinate = QPointF(-32.2138204, 115.0387413)
        self.zoom = 3
        self.mapLayer = TMSLayer('CRUSE:World_Bathymetric_Heightmap',
                                 self.canvasSize, self.centreCoordinate, 3)
        self.mapLayerHandle = self.scene.addWidget(self.mapLayer)
        self.setCentralWidget(self.view)
        self.mapLayer.setFocus()
Exemplo n.º 7
0
 def zoom(self, factor):
     """缩放
     :param factor: 缩放的比例因子
     """
     _factor = self.graphicsView.transform().scale(factor, factor).mapRect(
         QRectF(0, 0, 1, 1)).width()
     if _factor < 0.07 or _factor > 100:
         # 防止过大过小
         return
     if factor >= 1:
         if self.frame.scaleCnt >= 10:
             QtBubbleLabel.ShowMsgEx(self, "已经最大")
             return
         self.frame.scaleCnt += 1
     else:
         if self.frame.scaleCnt <= -10:
             QtBubbleLabel.ShowMsgEx(self, "已经最小")
             return
         self.frame.scaleCnt -= 1
     self.graphicsView.scale(factor, factor)
Exemplo n.º 8
0
    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem,
              index: QWidget) -> None:
        """
		Paint the graphics of the action with the ports.

		:param painter: This draws the widget.
		:type painter: QPainter
		:param option: Option for the style of graphic.
		:type option: QStyleOptionGraphicsItem
		:param index: Index for the painted graphic.
		:type index: QWidget
		:return: None
		:rtype: NoneType
		"""

        self.placePorts()
        painter.setBrush(self.color)
        x, y, width, height = self.getActionRect(self._action.getInputPorts(),
                                                 self._action.getOutputPorts())
        painter.drawRect(QRectF(x, y, width, height))
Exemplo n.º 9
0
    def __init__(self, simulator, desc):
        super().__init__(simulator, desc)

        self.setRect(QRectF(QPoint(), self._SIZE))

        self._inputs = list()

        r = self.rect()

        pin = Pin(self, desc.get_pin('out'))
        pin.setPos(_pin_pos(self.rect(), 1, 0.5))
        pin.setZValue(1)

        pen = QPen(Qt.black, 2, c=Qt.RoundCap)
        ext1 = QGraphicsLineItem(r.right() + _EXT_LENGTH,
                                 r.height() / 2, r.right(),
                                 r.height() / 2, self)
        ext1.setPen(pen)
        ext1.setFlag(QGraphicsItem.ItemStacksBehindParent)

        self._setup_inputs()
    def getPortGraphicsAtPos(self, x: float, y: float) -> None:
        """
		If there is a port at the position x, y, return it. The port does not have to be the
		item with the greatest Z value. This is different from the scene.itemAt function which only
		gets the top item.
		
		:param x: the scene x coordinate.
		:type x: float
		:param y: the scene y coordinate.
		:type y: float
		:return: the port graphics item at position (x, y)
		:rtype: PortGraphics
		"""
        rect = QRectF(x - 1, y - 1, 2, 2)
        items = self.scene().items(rect)

        # get the port graphics under the mouse if it exists.
        for item in items:
            if type(item) == PortGraphics:
                return item
        return None
Exemplo n.º 11
0
 def export_as_pdf(self, checked=False):
     self.qsettings.beginGroup(self.settings_group)
     file_path, _ = get_save_file_name_in_last_dir(
         self.qsettings, "exportGraphAsPDF", self, "Export as PDF...", self._get_base_dir(), "PDF files (*.pdf)"
     )
     self.qsettings.endGroup()
     if not file_path:
         return
     view = self.ui.graphicsView
     source = view._get_viewport_scene_rect()
     current_zoom_factor = view.zoom_factor
     view._zoom(1.0 / current_zoom_factor)
     self.scene.clearSelection()
     printer = QPrinter()
     printer.setPaperSize(source.size(), QPrinter.Point)
     printer.setOutputFileName(file_path)
     painter = QPainter(printer)
     self.scene.render(painter, QRectF(), source)
     painter.end()
     view._zoom(current_zoom_factor)
     self._insert_open_file_button(file_path)
Exemplo n.º 12
0
    def on_target_viewport_visible_scene_rect_changed(self, visible: QRectF):
        scene = self._target_view.scene()
        if scene is None:
            return

        x = (visible.x() - scene.sceneRect().x()) * self._scale
        y = (visible.y() - scene.sceneRect().y()) * self._scale
        width = visible.width() * self._scale
        height = visible.height() * self._scale
        mm_scene_w = self.sceneRect().width()
        mm_scene_h = self.sceneRect().height()

        minimap_vp_rect = QRectF()
        minimap_vp_rect.setTopLeft(
            QPoint(int(clamp(x, 0, mm_scene_w)), int(clamp(y, 0, mm_scene_h))))
        minimap_vp_rect.setBottomRight(
            QPoint(int(clamp(x + width, 0, mm_scene_w)),
                   int(clamp(y + height, 0, mm_scene_h))))

        self._minimap_target_viewport_box.set_viewport_rect(minimap_vp_rect)
        self._minimap_target_viewport_box.update()
Exemplo n.º 13
0
    def boundingRect(self) -> QRectF:
        """
		Defines the rectangle bounding the WireGraphics object.

		:return: A QRectF object.
		:rtype: QRectF
		"""
        xVals = [x for x, y in self._pathPoints]
        yVals = [y for x, y in self._pathPoints]

        xMax = max(xVals)
        yMax = max(yVals)
        xMin = min(xVals)
        yMin = min(yVals)

        width = xMax - xMin + WireGraphics.PEN_WIDTH
        height = yMax - yMin + WireGraphics.PEN_WIDTH
        x = xMin - WireGraphics.PEN_WIDTH / 2
        y = yMin - WireGraphics.PEN_WIDTH / 2

        return QRectF(x, y, width, height)
Exemplo n.º 14
0
 def updateHist(self, curve, redraw=True):
     """
     Update the channel histogram displayed under the curve
     @param curve:
     @type curve:
     @param redraw:
     @type redraw
     """
     sc = self.scene()
     if curve is sc.cubicRGB:
         curve.histImg = sc.layer.inputImg().histogram(size=sc.axeSize, bgColor=sc.bgColor, chans=[], mode='Luminosity')
     elif curve is sc.cubicR:
         curve.histImg = sc.layer.inputImg().histogram(size=sc.axeSize, bgColor=sc.bgColor, chans=channelValues.Red)
     elif curve is sc.cubicG:
         curve.histImg = sc.layer.inputImg().histogram(size=sc.axeSize, bgColor=sc.bgColor, chans=channelValues.Green)
     elif curve is sc.cubicB:
         curve.histImg = sc.layer.inputImg().histogram(size=sc.axeSize, bgColor=sc.bgColor, chans=channelValues.Blue)
     # Force to redraw histogram
     if redraw:
         sc.invalidate(QRectF(0.0, -sc.axeSize, sc.axeSize, sc.axeSize),
                         sc.BackgroundLayer)
    def drawProgress(self, painter: QPainter) -> None:
        painter.save()

        width: int = self.width()
        height: int = self.height()
        side: int = min(width, height)
        radius: int = 99 - self.__borderWidth

        # 绘制外圆
        pen: QPen = QPen()
        pen.setWidth(self.__borderWidth)
        pen.setColor(self.__borderColor)
        painter.setPen(pen if self.__borderWidth > 0 else Qt.NoPen)
        painter.setBrush(self.__bgColor)

        # 平移坐标轴中心, 等比例缩放
        rectCircle: QRect = QRect(-radius, -radius, radius * 2, radius * 2)
        painter.translate(width / 2, height / 2)
        painter.scale(side / 200.0, side / 200.0)
        painter.drawEllipse(rectCircle)

        # 绘制圆弧进度
        pen.setWidth(self.__lineWidth)
        pen.setColor(self.__lineColor)
        painter.setPen(pen)

        offset: int = radius - self.__lineWidth - 5
        rectArc: QRectF = QRectF(-offset, -offset, offset * 2, offset * 2)
        startAngle: int = offset * 16
        spanAngle: int = int(-self.__value * 16)
        painter.drawArc(rectArc, startAngle, spanAngle)

        # 绘制进度文字
        font: QFont = QFont()
        font.setPixelSize(offset - 15)
        painter.setFont(font)
        strValue: str = str(int(self.__value) * 100 // 360) + '%'
        painter.drawText(rectCircle, Qt.AlignCenter, strValue)

        painter.restore()
Exemplo n.º 16
0
    def ShowImg(self, isShowWaifu=True):
        p = self.pictureData.get(self.curIndex)

        if not p or (not p.data):
            self.qtTool.SetData(state=QtFileData.Downloading)
            self.graphicsItem.setPixmap(QPixmap())
            self.qtTool.modelBox.setEnabled(False)
            return
        if config.CanWaifu2x:
            self.qtTool.modelBox.setEnabled(True)
        assert isinstance(p, QtFileData)
        if not isShowWaifu:
            p2 = p.data
            self.qtTool.SetData(waifuSize=QSize(0, 0), waifuDataLen=0)
        elif p.waifuData:
            p2 = p.waifuData
            self.qtTool.SetData(waifuSize=p.waifuQSize,
                                waifuDataLen=p.waifuDataSize,
                                waifuTick=p.waifuTick)
        else:
            p2 = p.data

        self.qtTool.SetData(pSize=p.qSize,
                            dataLen=p.size,
                            state=p.state,
                            waifuState=p.waifuState)
        self.qtTool.UpdateText(p.model)

        self.frame.pixMap = QPixmap()
        if config.IsLoadingPicture:
            self.frame.pixMap.loadFromData(p2)
        self.graphicsItem.setPixmap(self.frame.pixMap)
        self.graphicsView.setSceneRect(
            QRectF(
                QPointF(0, 0),
                QPointF(self.frame.pixMap.width(),
                        self.frame.pixMap.height())))
        self.frame.ScalePicture()
        self.CheckLoadPicture()
        return True
Exemplo n.º 17
0
    def __init__(self, toolbox, icon_file, icon_color, background_color):
        """Base class for project item icons drawn in Design View.

        Args:
            toolbox (ToolBoxUI): QMainWindow instance
            icon_file (str): Path to icon resource
            icon_color (QColor): Icon's color
            background_color (QColor): Background color
        """
        super().__init__()
        self._toolbox = toolbox
        self.icon_file = icon_file
        self._moved_on_scene = False
        self._previous_pos = QPointF()
        self._current_pos = QPointF()
        self.icon_group = {self}
        self.renderer = QSvgRenderer()
        self.svg_item = QGraphicsSvgItem(self)
        self.colorizer = QGraphicsColorizeEffect()
        self.setRect(
            QRectF(-self.ITEM_EXTENT / 2, -self.ITEM_EXTENT / 2,
                   self.ITEM_EXTENT, self.ITEM_EXTENT))
        self.text_font_size = 10  # point size
        # Make item name graphics item.
        self._name = ""
        self.name_item = QGraphicsSimpleTextItem(self._name, self)
        self.set_name_attributes()  # Set font, size, position, etc.
        # Make connector buttons
        self.connectors = dict(
            bottom=ConnectorButton(self, toolbox, position="bottom"),
            left=ConnectorButton(self, toolbox, position="left"),
            right=ConnectorButton(self, toolbox, position="right"),
        )
        # Make exclamation and rank icons
        self.exclamation_icon = ExclamationIcon(self)
        self.execution_icon = ExecutionIcon(self)
        self.rank_icon = RankIcon(self)
        brush = QBrush(background_color)
        self._setup(brush, icon_file, icon_color)
        self.activate()
    def _draw_item_line(self, p: QPainter) -> None:
        """
        绘制项目周边的线条
        :param p: 画刷
        :return: None
        """
        if self._m_start_rect.isNull():
            return

        if self._m_item_line_style == self.ItemLineStyle.ItemNone:
            return
        elif self._m_item_line_style == self.ItemLineStyle.ItemTop:
            p1 = self._m_start_rect.topLeft()
            p2 = self._m_start_rect.topRight()
        elif self._m_item_line_style == self.ItemLineStyle.ItemRight:
            p1 = self._m_start_rect.topRight()
            p2 = self._m_start_rect.bottomRight()
        elif self._m_item_line_style == self.ItemLineStyle.ItemBottom:
            p1 = self._m_start_rect.bottomLeft()
            p2 = self._m_start_rect.bottomRight()
        elif self._m_item_line_style == self.ItemLineStyle.ItemLeft:
            p1 = self._m_start_rect.topLeft()
            p2 = self._m_start_rect.bottomLeft()
        elif self._m_item_line_style == self.ItemLineStyle.ItemRect:
            p1 = self._m_start_rect.topLeft()
            p2 = self._m_start_rect.bottomRight()
        else:
            return

        p.save()
        line_pen = QPen()
        line_pen.setColor(self._m_item_line_color)
        line_pen.setWidth(self._m_item_line_width)
        p.setPen(line_pen)
        if self._m_item_line_style == self.ItemLineStyle.ItemRect:
            p.drawRoundedRect(QRectF(p1, p2), self._m_item_radius, self._m_item_radius)
        else:
            p.drawLine(p1, p2)

        p.restore()
Exemplo n.º 19
0
 def paintEvent(self, event):
     if not self.board:
         return
     self.base_square_size = min(self.size().width(), self.size().height())
     painter = QPainter(self)
     painter.setPen(Qt.NoPen)
     painter.setBrush(self.palette().color(self.backgroundRole()))
     painter.drawRect(self.rect())
     board_radius = len(self.board.data) // 2
     square_size = self.base_square_size / board_radius / 2
     offset_x = self.size().width() // 2
     offset_y = self.size().height() // 2
     for y in range(-board_radius, board_radius):
         for x in range(-board_radius, board_radius):
             if (color := self.board.get_square_color(x, y)) != board.NO_COLOR:
                 painter.setBrush(QBrush(self.square_colors[
                     self.board.get_square_parity(x, y) if self.checkerboard_enabled else board.BLACK, color
                 ]))
                 painter.drawRect(QRectF(
                     x * square_size + offset_x, y * square_size + offset_y,
                     square_size + 0.5, square_size + 0.5
                 ))
Exemplo n.º 20
0
    def paint(self, painter, option, widget):
        """Implementation.

    Handle drawing "ghost" tiles when hovering over grid cells.
    """

        super().paint(painter, option, widget)

        tool = self.editor.currentTool()
        if tool is None:
            return

        pixmap = tool._selectedTile
        if self._hoveredCell and pixmap:
            scenePos = Editor.gridToScene(self._hoveredCell)
            fragment = QPainter.PixmapFragment.create(
                scenePos + QPointF(pixmap.width() / 2,
                                   pixmap.height() / 2),
                QRectF(QPointF(0, 0), pixmap.size()),
                rotation=tool._tileRotation,
                opacity=0.75)
            painter.drawPixmapFragments(fragment, 1, pixmap)
Exemplo n.º 21
0
    def init_scene(self, empty=False):
        """Resize scene and add a link drawer on scene.
        The scene must be cleared before calling this.

        Args:
            empty (boolean): True when creating a new project
        """
        self.link_drawer = LinkDrawer(self._toolbox)
        self.scene().addItem(self.link_drawer)
        if len(self.scene().items()) == 1:
            # Loaded project has no project items
            empty = True
        if not empty:
            # Reset scene rectangle to be as big as the items bounding rectangle
            items_rect = self.scene().itemsBoundingRect()
            margin_rect = items_rect.marginsAdded(QMarginsF(20, 20, 20, 20))  # Add margins
            self.scene().setSceneRect(margin_rect)
        else:
            rect = QRectF(0, 0, 401, 301)
            self.scene().setSceneRect(rect)
        self.scene().update()
        self.reset_zoom()
Exemplo n.º 22
0
    def update_shape(self):
        """Causes recompilation of the whole shape."""

        if self.main_widget is not None:  # maybe the main_widget got resized
            self.main_widget_proxy.setMaximumSize(self.main_widget.size())
            self.widget.adjustSize()

        self.layout.activate()
        self.layout.invalidate()
        # both very essential; repositions everything in case content has changed (inputs/outputs/widget)

        self.width = self.boundingRect().width()
        self.height = self.boundingRect().height()
        rect = QRectF(QPointF(-self.width/2, -self.height/2),
                      QPointF(self.width/2, self.height/2))
        self.widget.setPos(rect.left(), rect.top())

        if not self.parent_node.design_style == 'extended':
            self.title_label.setPos(QPointF(-self.title_label.boundingRect().width()/2,
                                            -self.title_label.boundingRect().height()/2))

        self.flow.viewport().update()
Exemplo n.º 23
0
 def initFixedPoints(self):
     """
     Add 2 boundary control points and a central one.
     """
     axeSize = self.size
     rect = QRectF(0.0, -axeSize, axeSize, axeSize)
     self.fixedPoints = [
         activeSplinePoint(0,
                           0,
                           persistent=True,
                           rect=rect,
                           parentItem=self),
         activeSplinePoint(axeSize / 2,
                           -axeSize / 2,
                           rect=rect,
                           parentItem=self),
         activeSplinePoint(axeSize,
                           -axeSize,
                           persistent=True,
                           rect=rect,
                           parentItem=self)
     ]
Exemplo n.º 24
0
    def reload_target_scene(self):
        """
        Reload scene from target view, scaling the minimap view to properly fit the scene into view while preserving
        scene aspect ratio.
        """
        scene = self._target_view.scene()
        if scene is None:
            return

        # Scale target scene dimensions to fit within widget bounds, preserving scene aspect ratio
        mm_max_w = self.maximumWidth()
        mm_max_h = self.maximumHeight()
        scene_rect = scene.sceneRect()
        scene_w = scene_rect.width()
        scene_h = scene_rect.height()

        if mm_max_w == 0 or mm_max_h == 0 or scene_w == 0 or scene_h == 0:
            return

        minimap_aspect_ratio = mm_max_w / mm_max_h
        scene_aspect_ratio = scene_w / scene_h

        if minimap_aspect_ratio < scene_aspect_ratio:
            self._scale = mm_max_w / scene_w
        else:
            self._scale = mm_max_h / scene_h

        scaled_scene_rect = QRectF(0, 0, int(scene_w * self._scale),
                                   int(scene_h * self._scale))
        self.resize(scaled_scene_rect.width(), scaled_scene_rect.height())
        self._minimap_scene.setSceneRect(scaled_scene_rect)
        self.setSceneRect(scaled_scene_rect)
        self._minimap_target_scene_viewer.set_scene_rect(scaled_scene_rect)
        self._minimap_target_viewport_box.set_scene_rect(scaled_scene_rect)

        self._minimap_target_scene_viewer.update_scene_drawing()
        self.on_target_viewport_visible_scene_rect_changed(
            self._target_view.visible_scene_rect)
Exemplo n.º 25
0
    def __init__(self, parent, toolbox, position="left"):
        """Connector button graphics item. Used for Link drawing between project items.

        Args:
            parent (QGraphicsItem): Project item bg rectangle
            toolbox (ToolBoxUI): QMainWindow instance
            position (str): Either "top", "left", "bottom", or "right"
        """
        super().__init__(parent)
        self._parent = parent
        self._toolbox = toolbox
        self.position = position
        self.links = list()
        pen = QPen(Qt.black, 0.5, Qt.SolidLine)
        self.setPen(pen)
        self.setBrush(self.brush)
        parent_rect = parent.rect()
        extent = 0.2 * parent_rect.width()
        rect = QRectF(0, 0, extent, extent)
        if position == "top":
            rect.moveCenter(
                QPointF(parent_rect.center().x(),
                        parent_rect.top() + extent / 2))
        elif position == "left":
            rect.moveCenter(
                QPointF(parent_rect.left() + extent / 2,
                        parent_rect.center().y()))
        elif position == "bottom":
            rect.moveCenter(
                QPointF(parent_rect.center().x(),
                        parent_rect.bottom() - extent / 2))
        elif position == "right":
            rect.moveCenter(
                QPointF(parent_rect.right() - extent / 2,
                        parent_rect.center().y()))
        self.setRect(rect)
        self.setAcceptHoverEvents(True)
        self.setCursor(Qt.PointingHandCursor)
Exemplo n.º 26
0
    def paintEvent(self, event):
        pos1 = self.btn_point1.pos()
        pos2 = self.btn_point2.pos()
        pos3 = self.btn_point3.pos()
        pos4 = self.btn_point4.pos()

        point_list = np.array([(pos1.x(), pos1.y()), (pos2.x(), pos2.y()),
                               (pos3.x(), pos3.y()), (pos4.x(), pos4.y())
                               ]) + self.btn_point4.width() / 2
        point_list = order_points(point_list)

        painter = QPainter()
        painter.begin(self)
        painter.setPen(Qt.NoPen)
        painter.fillRect(self.rect(), QColor(190, 190, 190, 255))

        if self.scaled_img:
            painter.drawPixmap(self.img_rect, self.scaled_img)

            if self.scaled_img_valid != 0:
                painter.setPen(QPen(Qt.green, 1))
                painter.drawLine(point_list[0, 0], point_list[0, 1],
                                 point_list[1, 0], point_list[1, 1])
                painter.drawLine(point_list[1, 0], point_list[1, 1],
                                 point_list[2, 0], point_list[2, 1])
                painter.drawLine(point_list[2, 0], point_list[2, 1],
                                 point_list[3, 0], point_list[3, 1])
                painter.drawLine(point_list[3, 0], point_list[3, 1],
                                 point_list[0, 0], point_list[0, 1])
            else:
                painter.setFont(QFont('宋体', 100, QFont.Black, True))
                painter.setPen(QPen(Qt.red))
                painter.drawText(
                    QRectF(0.0, 0.0, self.scaled_img.width(),
                           self.scaled_img.height()),
                    Qt.AlignCenter | Qt.AlignTop, "已作废")

        painter.end()
Exemplo n.º 27
0
    def reload(self):
        self._reset_scene()

        scene = self.scene()

        # if self.workspace.cartprograph.connection_status == False:
        #     f = QFont(Conf.code_font)
        #     f.setPointSize(14)
        #     txt = scene.addText("Note: Disconnected from Cartprograph Server,\nuse Plugins->Connect to Cartprograph", f)
        #     txt.setDefaultTextColor(QtCore.Qt.red)
        #     return

        if self.graph is None:
            return

        node_sizes = {node: (node.width, node.height) for node in self.graph.nodes()}
        layout = GraphLayouter(self.graph, node_sizes)

        for edge in layout.edges:
            arrow = QCartEdge(edge)
            self.workspace.cartprograph.edges[(edge.src.id, edge.dst.id)] = arrow
            arrow.setPos(QPointF(*edge.coordinates[0]))
            scene.addItem(arrow)

        for node, (x, y) in layout.node_coordinates.items():
            node.setPos(x, y)
            scene.addItem(node)

        rect = scene.itemsBoundingRect()
        scene.setSceneRect(
            QRectF(
                rect.x() - 200,
                rect.y() - 200,
                rect.width() + 400,
                rect.height() + 400,
            )
        )
Exemplo n.º 28
0
 def resizeEvent(self, r: QResizeEvent) -> None:
     """
     Qt Resize Event - does two things:
     1) applies rounded corners if window transparency has been disabled
     2) ensures resizer widgets and titlebar buttons stay in place
     TODO: the 'rounded_corner_px' value is harcoded. It relates to in '.TitleTabBar::tab' in
           widgetstyle/tabwidget_titlebar.py (border-width and border-image QSS attribute).
           Action: investigate a way so that this value doesn't have to be hard-coded.
     """
     # if transparency is turned off, set a mask for some basic rounded corners:
     if not self.__transparent_window and self.__style.window.WINDOW_CORNER_RADIUS_PX > 0:
         path = QPainterPath()
         path.addRoundedRect(
             QRectF(self.rect()),
             self.__style.window.WINDOW_CORNER_RADIUS_PX +
             1,  # add 1 to avoid drawing artifacts
             self.__style.window.WINDOW_CORNER_RADIUS_PX + 1)
         reg = QRegion(path.toFillPolygon().toPolygon())
         self.setMask(reg)
     # adjust window button positions
     if not isinstance(self.__window, QDIALOG_TYPES):
         self.resizer_bl.adjust_resizers(self.geometry(
         ))  # adjusting one resizer adjusts all other resizers too
     if self.__window_buttons_position == WINDOW_BUTTONS_RIGHT:
         self.__move_window_buttons()
     # if a titlebar tab widget is set, mask it so that the empty area can be used to drag the window
     if self.__tab_widget is not None:
         width = 0
         tab_bar = self.__tab_widget.tabBar()
         for i in range(0,
                        tab_bar.count() -
                        1):  # don't count invisible tab at end
             if tab_bar.isTabVisible(i):
                 width += tab_bar.tabRect(i).width()
         rounder_corner_px = 8  # TODO  # related to hardcoded border-image value in widgetstyle/tabwidget_titlebar.py
         r = QRect(0, 0, width + rounder_corner_px, self.__titlebar_height)
         self.__tab_widget.tabBar().setMask(r)
Exemplo n.º 29
0
    def update_shape(self):
        """Causes recompilation of the whole shape."""
        # if not self.initializing:   # just to make sure
        #     self.rebuild_ui()       # (hopefully) temporary fix -> see rebuild_ui() docstring

        if self.main_widget is not None:  # maybe the main_widget got resized
            self.main_widget_proxy.setMaximumSize(self.main_widget.size())
            self.widget.adjustSize()
            self.widget.adjustSize()

        self.body_layout.invalidate()
        self.layout.invalidate()
        self.layout.activate()
        # very essential; repositions everything in case content has changed (inputs/outputs/widget)

        if self.parent_node.design_style == 'minimalistic':

            # making it recompute its true minimumWidth here
            self.widget.adjustSize()

            if self.layout.minimumWidth() < self.title_label.width + 15:
                self.layout.setMinimumWidth(self.title_label.width + 15)
                self.layout.activate()

        self.width = self.boundingRect().width()
        self.height = self.boundingRect().height()
        rect = QRectF(QPointF(-self.width / 2, -self.height / 2),
                      QPointF(self.width / 2, self.height / 2))
        self.widget.setPos(rect.left(), rect.top())

        if not self.parent_node.design_style == 'extended':
            self.title_label.setPos(
                QPointF(-self.title_label.boundingRect().width() / 2,
                        -self.title_label.boundingRect().height() / 2))

        self.flow.viewport().update()
Exemplo n.º 30
0
    def paintPagesView(self):
        # This method paints the page layout, nothing more
        # It also paints the background at page breaks
        # The design is drawn only when the editor is in page mode.
        if (self.m_usePageMode):
            # Draw page breaks
            pageWidth = self.m_pageMetrics.pxPageSize().width()
            pageHeight = self.m_pageMetrics.pxPageSize().height()

            p = QPainter(self.viewport())
            borderPen = QPen(self.palette().dark(), 1)

            curHeight = pageHeight - (self.verticalScrollBar().value() %
                                      pageHeight)

            # Horizontal offset if there is a scroll bar
            horizontalDelta = self.horizontalScrollBar().value()

            # Paint page views while there are remotely more visible pages
            while (curHeight < pageHeight + self.height()):

                p.setRenderHint(QPainter.Antialiasing)
                path = QPainterPath()
                # In painting page, height of the rect is (pageHeight - 10)
                # to give page break
                pageLayout = QRectF(0 - horizontalDelta,
                                    curHeight - pageHeight, pageWidth,
                                    pageHeight - 10)
                path.addRect(pageLayout)
                p.fillPath(path, Qt.white)

                p.setPen(borderPen)
                p.drawPath(path)

                # Go to next page
                curHeight += pageHeight