当前位置: 首页>>代码示例>>Python>>正文


Python QGraphicsTextItem.setFont方法代码示例

本文整理汇总了Python中PyQt5.QtWidgets.QGraphicsTextItem.setFont方法的典型用法代码示例。如果您正苦于以下问题:Python QGraphicsTextItem.setFont方法的具体用法?Python QGraphicsTextItem.setFont怎么用?Python QGraphicsTextItem.setFont使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtWidgets.QGraphicsTextItem的用法示例。


在下文中一共展示了QGraphicsTextItem.setFont方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ActionItem

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class ActionItem(GraphicsItem):
    def __init__(self, model_item: SimulatorItem, parent=None):
        super().__init__(model_item=model_item, parent=parent)

        self.setFlag(QGraphicsTextItem.ItemIsPanel, True)

        self.text = QGraphicsTextItem(self)
        self.text.setFont(self.font)

    def update_flags(self):
        if self.scene().mode == 0:
            self.set_flags(is_selectable=True, is_movable=True, accept_hover_events=True, accept_drops=True)

    def update_position(self, x_pos, y_pos):
        self.setPos(x_pos, y_pos)
        start_x = (self.scene().items_width() - self.labels_width()) / 2
        self.number.setPos(start_x, 0)
        start_x += self.number.boundingRect().width()
        self.text.setPos(start_x, 0)

        width = self.scene().items_width()
        self.prepareGeometryChange()
        self.bounding_rect = QRectF(0, 0, width, self.childrenBoundingRect().height() + 5)

    def labels_width(self):
        width = self.number.boundingRect().width()
        width += self.text.boundingRect().width()
        return width
开发者ID:jopohl,项目名称:urh,代码行数:30,代码来源:ActionItem.py

示例2: createImage

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
    def createImage(self, transform):
        if self.type == DemoTextItem.DYNAMIC_TEXT:
            return None

        sx = min(transform.m11(), transform.m22())
        sy = max(transform.m22(), sx)

        textItem = QGraphicsTextItem()
        textItem.setHtml(self.text)
        textItem.setTextWidth(self.textWidth)
        textItem.setFont(self.font)
        textItem.setDefaultTextColor(self.textColor)
        textItem.document().setDocumentMargin(2)

        w = textItem.boundingRect().width()
        h = textItem.boundingRect().height()
        image = QImage(int(w * sx), int(h * sy),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.scale(sx, sy)
        style = QStyleOptionGraphicsItem()
        textItem.paint(painter, style, None)

        return image
开发者ID:death-finger,项目名称:Scripts,代码行数:27,代码来源:demotextitem.py

示例3: AnimatedClock

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class AnimatedClock(QGraphicsView):
    def __init__(self, parent=None):
        QGraphicsView.__init__(self, parent)
        self.updateSecs = 0.5
        # Border
        self.setLineWidth(0)
        self.setFrameShape(QtWidgets.QFrame.NoFrame)
        # Size
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHeightForWidth(True)
        self.setSizePolicy(sizePolicy)
        # No scrollbars
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # Scene
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.setBackgroundBrush(QColor("black"))
        # Text of clock
        self.textItem = QGraphicsTextItem()
        self.textItem.color = QColor(QColor("black"))
        self.textItem.setFont(QFont("Segoe UI", 80))
        self.textItem.setDefaultTextColor(QColor("white"))
        self.textItem.setHtml("")
        self.textItem.setZValue(20)
        self.scene.addItem(self.textItem)
        # Start ticking
        self.start()

    def sizeHint(self):
        return QSize(300, 150)

    def start(self):
        self.updateTimer = QTimer()
        self.updateTimer.setInterval(self.updateSecs * 990)
        self.updateTimer.timeout.connect(self.updateClock)
        self.updateTimer.start()
        print("Animated clock - starting")

    def stop(self):
        if self.updateTimer != None:
            self.updateTimer.stop()
        print("Animated clock - stopping")

    def updateClock(self):
        localtime = time.localtime()
        timeString = time.strftime("%H:%M:%S", localtime)
        self.textItem.setHtml(timeString)
        width = self.frameGeometry().width()
        self.textItem.setFont(QFont("Segoe UI", width / 8))
        self.textItem.update()

    def heightForWidth(self, width):
        return width * .32

    def keyPressEvent(self, event): #QKeyEvent
        event.ignore()
开发者ID:robdobsn,项目名称:KitchenProjectorCalPhotoApp,代码行数:59,代码来源:AnimatedClock.py

示例4: showImage

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
    def showImage(self):
        (newImg, newImgInfo) = self.loadImage()
        # return PicItem(Pixmap(QPixmap(newImg)), -1, -1, xFactor, yFactor, newImgInfo)
        self.scene.clear()
        imgSz = newImgInfo.imgSize
        self.setSceneRect(QRectF(0,0,imgSz.width(), imgSz.height()))
        pixMap = QPixmap.fromImage(newImg)
        # # pixMap.setWidth(self.width())
        pixMapItem = self.scene.addPixmap(pixMap)
        # pixMapItem.setPos(50,50)
        # self.fitInView(QRectF(0, 0, self.width(), self.height()), Qt.KeepAspectRatio)
        # Add caption
        caption = QGraphicsTextItem()
        caption.setDefaultTextColor(QColor(255,255,255))
        caption.setPos(0, self.height()*0.94)
        caption.setFont(QFont("Segoe UI", 30))
        caption.setTextWidth(self.width())
        # caption.setPos(100, 100)
        # caption.setTextWidth(1500)
        # if newImgInfo.createDate is not None:
        #     caption.setPlainText(newImgInfo.createDate.format());
        # else:
        #     caption.setPlainText("Image is called bananas");
        # print("Tags", newImgInfo.tags)
        # tagStr = ""
        # for tag in newImgInfo.tags:
        #     if tag != "Duplicate":
        #         tagStr += (", " if len(tagStr) != 0 else "") + tag
        # if tagStr == "":
        #     tagStr = "NO TAGS"
        # captionStr = '<h1 style="text-align:center;width:100%">' + tagStr + '</h1>'
        # if newImgInfo.createDate is not None:
        #     print(newImgInfo.createDate.format())
        #     captionStr += '<BR><h2>' + newImgInfo.createDate.format() + '</h2>'

        captionStr = ""
        try:
            if newImgInfo.rating is not None:
                for i in range(newImgInfo.rating):
                    captionStr += "&#x2605;"
                for i in range(5-newImgInfo.rating):
                    captionStr += "&#x2606;"
            if newImgInfo.mainDate is not None:
                if len(captionStr) != 0:
                    captionStr += "  "
                captionStr += newImgInfo.mainDate.strftime("%d %b %Y")
        except Exception as excp:
            print("StaticPhotos: Cannot set caption")
        captionStr = '<div style="background-color:#000000;text-align: right;padding-right:10dp;">' + captionStr + "</div>"
        print(captionStr)
        caption.setHtml(captionStr)
        self.scene.addItem(caption)
        self.scene.update()
开发者ID:robdobsn,项目名称:KitchenProjectorCalPhotoApp,代码行数:55,代码来源:StaticPhotos.py

示例5: ParticipantItem

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class ParticipantItem(QGraphicsItem):
    def __init__(self, model_item: Participant, parent=None):
        super().__init__(parent)

        self.model_item = model_item

        self.text = QGraphicsTextItem(self)

        self.line = QGraphicsLineItem(self)
        self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))

        self.refresh()

    def update_position(self, x_pos=-1, y_pos=-1):
        if x_pos == -1:
            x_pos = self.x_pos()

        if y_pos == -1:
            y_pos = self.line.line().y2()

        self.text.setPos(x_pos - (self.text.boundingRect().width() / 2), 0)
        self.line.setLine(x_pos, 30, x_pos, y_pos)

    def x_pos(self):
        return self.line.line().x1()

    def width(self):
        return self.boundingRect().width()

    def refresh(self):
        self.text.setPlainText("?" if not self.model_item else self.model_item.shortname)
        if hasattr(self.model_item, "simulate") and self.model_item.simulate:
            font = QFont()
            font.setBold(True)
            self.text.setFont(font)
            self.text.setDefaultTextColor(Qt.darkGreen)
            self.line.setPen(QPen(Qt.darkGreen, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        else:
            self.text.setFont(QFont())
            self.text.setDefaultTextColor(constants.LINECOLOR)
            self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))

    def boundingRect(self):
        return self.childrenBoundingRect()

    def paint(self, painter, option, widget):
        pass
开发者ID:jopohl,项目名称:urh,代码行数:49,代码来源:ParticipantItem.py

示例6: create_map_points

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
 def create_map_points(self):
     self.map_points_text_items = []
     self.map_points_items = []
     for map_point in self.map_data.map_points:
         color = QColor().fromRgb(map_point.r, map_point.g, map_point.b)
         rect = QGraphicsRectItem(
             QRectF(
                 QPointF(map_point.x, map_point.y),
                 QSizeF(5 / self.scale_ratio, 5 / self.scale_ratio)
             )
         )
         rect.setPen(QPen(Qt.black, 1 / self.scale_ratio))
         rect.setBrush(color)
         self.map_points_items.append(rect)
         text = QGraphicsTextItem(map_point.text)
         text.setDefaultTextColor(color)
         text.setPos(map_point.x, map_point.y)
         text.setFont(QFont('Times New Roman', 8 / self.scale_ratio, 2))
         self.map_points_text_items.append(text)
开发者ID:nomns,项目名称:Parse99,代码行数:21,代码来源:mapcanvas.py

示例7: drawAxis

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
    def drawAxis(self, data, points):

        xmin = data['xmin']
        xmax = data['xmax']
        ymin = data['ymin']
        ymax = data['ymax']
        xmarg = data['xmarg']
        ymarg = data['xmarg']
        xscale = data['xscale']
        yscale = data['yscale']

        scene = self.uiFunctionGraph.scene()

        scene.addLine(xmarg - 10, ymarg + 10, (xmax - xmin) * xscale + xmarg + 10, ymarg + 10)
        scene.addLine((xmax - xmin) * xscale + xmarg + 8, ymarg + 8, (xmax - xmin) * xscale + xmarg + 10, ymarg + 10)
        scene.addLine((xmax - xmin) * xscale + xmarg + 8, ymarg + 13, (xmax - xmin) * xscale + xmarg + 10, ymarg + 11)
        scene.addLine(xmarg - 10, ymarg + 10, xmarg - 10, (ymax - ymin) * yscale + ymarg - 10)
        scene.addLine(xmarg - 8, (ymax - ymin) * yscale + ymarg - 9, xmarg - 10, (ymax - ymin) * yscale + ymarg - 11)
        scene.addLine(xmarg - 12, (ymax - ymin) * yscale + ymarg - 8, xmarg - 10, (ymax - ymin) * yscale + ymarg - 10)

        y = ymin
        step = (ymax - ymin) / 4
        for i in range(5):
            scene.addLine(xmarg - 12, (y - ymin) * yscale + ymarg, xmarg - 8, (y - ymin) * yscale + ymarg)
            text = QGraphicsTextItem()
            text.setPos(0, (y - ymin) * yscale + ymarg - 7)
            text.setPlainText('%s' % format(round(y, 3), '.3f'))
            text.setFont(QFont('Sans', 6))
            scene.addItem(text)
            y += step
        
        x = xmin
        step = (xmax - xmin) / 19
        for i in range(20):
            scene.addLine((x - xmin) * xscale + xmarg, ymarg + 8, (x - xmin) * xscale + xmarg, ymarg + 12)
            text = QGraphicsTextItem()
            text.setPos((x - xmin) * xscale + xmarg - 14, ymarg + 10)
            text.setPlainText('%s' % format(round(x, 3), '.3f'))
            text.setFont(QFont('Sans', 6))
            scene.addItem(text)
            x += step
开发者ID:the0,项目名称:pyfrbs,代码行数:43,代码来源:analyst.py

示例8: define

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
    def define(self, cells):
        index = 0
        cell_sum = 0
        for y in range(self.height):
            for x in range(self.width):
                try:
                    required_bridges = int(cells[y][x])
                    new_island = Island(index, x, y, required_bridges)
                    self.islands.append(new_island)
                    self.grid[y][x] = new_island
                    text_item = QGraphicsTextItem(str(required_bridges))
                    text_item.setFont(self.font)
                    text_item.setPos(30*x+5, 30*y-2)
                    self.scene.addItem(text_item)
                    cell_sum += required_bridges
                    index += 1
                except ValueError:
                    pass

        if cell_sum % 2 == 0:
            self.total_required_bridges = int(cell_sum / 2)
            print("Found {} islands that require a total of {} bridges".format(index, self.total_required_bridges))
        else:
            print("The grid is not valid!")
开发者ID:0x4e84,项目名称:PythonSandBox,代码行数:26,代码来源:Grid.py

示例9: Edge

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]

#.........这里部分代码省略.........
    @property
    def end_point(self):
        ''' Compute connection end point - redefine in subclasses '''
        return self.mapFromScene(*self.edge['end']) \
               if self.edge.get('end') else None

    def bezier_set_visible(self, visible=True):
        ''' Display or hide the edge control points '''
        self.bezier_visible = visible
        for group in self.bezier[1:]:
            for ctrl_point in group:
                if visible:
                    ctrl_point.show()
                else:
                    ctrl_point.hide()
        if visible:
            self.end_connection.show()
            self.source_connection.show()
        else:
            self.end_connection.hide()
            self.source_connection.hide()
        self.update()

    def mousePressEvent(self, event):
        ''' On a mouse click, display the control points '''
        self.bezier_set_visible(True)

  # pylint: disable=R0914
    def reshape(self):
        ''' Update the shape of the edge (redefined function) '''
        path = QPainterPath()
        # If there is a starting point, draw a line to the first curve point
        if self.start_point:
            path.moveTo(self.source_connection.center)
            path.lineTo(self.bezier[0])
        else:
            path.moveTo(self.source_connection.center)
        # Loop over the curve points:
        for group in self.bezier[1:]:
            path.cubicTo(*[point.center for point in group])

        # If there is an ending point, draw a line to it
        if self.end_point:
            path.lineTo(self.end_connection.center)

        end_point = path.currentPosition()
        arrowhead = self.angle_arrow(path)
        path.lineTo(arrowhead[0])
        path.moveTo(end_point)
        path.lineTo(arrowhead[1])
        path.moveTo(end_point)
        try:
            # Add the transition label, if any (none for the START edge)
            font = QFont('arial', pointSize=8)
            metrics = QFontMetrics(font)
            label = self.edge.get('label', '')
            lines = label.split('\n')
            width = metrics.width(max(lines)) # longest line
            height = metrics.height() * len(lines)
            # lp is the position of the center of the text
            pos = self.mapFromScene(*self.edge['lp'])
            if not self.text_label:
                self.text_label = QGraphicsTextItem(
                                 self.edge.get('label', ''), parent=self)
            self.text_label.setX(pos.x() - width / 2)
            self.text_label.setY(pos.y() - height / 2)
            self.text_label.setFont(font)
            # Make horizontal center alignment, as dot does
            self.text_label.setTextWidth(self.text_label.boundingRect().width())
            fmt = QTextBlockFormat()
            fmt.setAlignment(Qt.AlignHCenter)
            cursor = self.text_label.textCursor()
            cursor.select(QTextCursor.Document)
            cursor.mergeBlockFormat(fmt)
            cursor.clearSelection()
            self.text_label.setTextCursor(cursor)
            self.text_label.show()
        except KeyError:
            # no label
            pass
        self.setPath(path)

    def __str__(self):
        ''' user-friendly information about the edge coordinates '''
        return('Edge between ' + self.edge['source'].name + ' and ' +
                self.edge['target'].name + str(self.edge['spline'][0]))

    def paint(self, painter, option, widget):
        ''' Apply anti-aliasing to Edge Connections '''
        painter.setRenderHint(QPainter.Antialiasing, True)
        super(Edge, self).paint(painter, option, widget)
        # Draw lines between connection points, if visible
        if self.bezier_visible:
            painter.setPen(
                    QPen(Qt.lightGray, 0, Qt.SolidLine))
            painter.setBrush(Qt.NoBrush)
            points_flat = [point.center
                           for sub1 in self.bezier[1:] for point in sub1]
            painter.drawPolyline([self.source_connection.center]
                                  + points_flat + [self.end_connection.center])
开发者ID:examon,项目名称:opengeode,代码行数:104,代码来源:Connectors.py

示例10: SimpleBlackbox

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class SimpleBlackbox(PyreeNode):
    """Blackbox node template with inputs on the left and outputs on the right"""
    # Here we define some information about the node
    author = "DrLuke"  # Author of this node (only used for namespacing, never visible to users)
    modulename = "simplebb"  # Internal name of the module, make this something distinguishable
    name = "Simple Blackbox"  # Human-readable name

    placeable = False  # Whether or not this node should be placeable from within the editor
    Category = ["Builtin"]  # Nested categories this Node should be sorted in

    # Description, similar to python docstrings (Brief summary on first line followed by a long description)
    description = """This node is the base class for all nodes.
    It should never be placeable in the editor. However if you DO see this in the editor, something went wrong!"""

    # Class implementing this node.
    implementation = BaseImplementation

    def defineIO(self):
        raise NotImplementedError("This method must be implemented in derived class")

    def addInput(self, type, name, displayname):
        self.inputs.append([type, name, displayname])

    def addOutput(self, type, name, displayname):
        self.outputs.append([type, name, displayname])

    def addIO(self):
        """Add/Update IO"""
        self.inputs = []
        self.outputs = []


        self.defineIO()


        indexOffset = 2
        verticalIoSpacing = 20  # Vertical Space between 2 IOs
        verticalIoStartOffset = (verticalIoSpacing * (max(len(self.inputs), len(self.outputs)) + indexOffset)) / 2

        horizontalIoDistance = 10

        maxInputWidth = 0
        maxOutputWidth = 0
        nodeTitleWidth = self.nodeTitle.boundingRect().width()
        titlePadding = 10

        horizontalTextToIoDistance = 5

        for ioDefinition in self.inputs:
            if ioDefinition[0] is not None:
                if ioDefinition[0] is execType:
                    ioDefinition.append(ExecInput(ioDefinition[0], parent=self, name=ioDefinition[1], displaystr=ioDefinition[2]))
                else:
                    ioDefinition.append(NodeInput(ioDefinition[0], parent=self, name=ioDefinition[1], displaystr=ioDefinition[2]))
                ioDefinition.append(QGraphicsTextItem(ioDefinition[2], ioDefinition[3]))
                maxInputWidth = max(maxInputWidth, ioDefinition[4].boundingRect().width())
                ioDefinition[4].setPos(QPointF(horizontalTextToIoDistance, - ioDefinition[3].boundingRect().height() / 2 - ioDefinition[4].boundingRect().height() / 4))
                self.IO[ioDefinition[1]] = ioDefinition[3]

        for ioDefinition in self.outputs:
            if ioDefinition[0] is not None:
                if ioDefinition[0] is execType:
                    ioDefinition.append(ExecOutput(ioDefinition[0], parent=self, name=ioDefinition[1], displaystr=ioDefinition[2]))
                else:
                    ioDefinition.append(NodeOutput(ioDefinition[0], parent=self, name=ioDefinition[1], displaystr=ioDefinition[2]))
                ioDefinition.append(QGraphicsTextItem(ioDefinition[2], ioDefinition[3]))
                maxOutputWidth = max(maxInputWidth, ioDefinition[4].boundingRect().width())
                ioDefinition[4].setPos(QPointF(- horizontalTextToIoDistance - ioDefinition[4].boundingRect().width(), - ioDefinition[3].boundingRect().height() / 2 - ioDefinition[4].boundingRect().height() / 4))
                self.IO[ioDefinition[1]] = ioDefinition[3]

        width = max(maxInputWidth + maxOutputWidth + horizontalIoDistance, nodeTitleWidth + titlePadding)
        height = verticalIoSpacing * (max(len(self.inputs), len(self.outputs)) + indexOffset - 1)
        self.mainRect.setRect(QRectF(-width/2, -height/2, width, height))

        for ioDefinition in self.inputs:
            if ioDefinition[0] is not None:
                ioDefinition[3].setPos(QPointF(-width/2, - verticalIoStartOffset + (self.inputs.index(ioDefinition) + indexOffset) * verticalIoSpacing))

        for ioDefinition in self.outputs:
            if ioDefinition[0] is not None:
                ioDefinition[3].setPos(QPointF(width / 2, - verticalIoStartOffset + (self.outputs.index(ioDefinition) + indexOffset) * verticalIoSpacing))

        self.nodeTitle.setPos(QPointF(- nodeTitleWidth / 2, -height / 2))

    def boundingRect(self):
        return self.mainRect.rect()

    def addGraphicsItems(self):
        self.mainRect = QGraphicsRectItem(QRectF(-15, -15, 30, 30), self)
        self.nodeTitle = QGraphicsTextItem(type(self).name, self)
        titleFont = QFont()
        titleFont.setBold(True)
        self.nodeTitle.setFont(titleFont)
        self.selectedChanged(self.isSelected())

    def selectedChanged(self, state):
        if state:
            self.mainRect.setPen(QPen(Qt.red))
        else:
            self.mainRect.setPen(QPen(Qt.black))
#.........这里部分代码省略.........
开发者ID:DrLuke,项目名称:gpnshader,代码行数:103,代码来源:baseModule.py

示例11: OcrArea

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class OcrArea(QGraphicsRectItem):
    ## static data
    resizeBorder = .0

    def __init__(self, pos, size, type_, parent = None, scene = None,
                 areaBorder = 2, index = 0, textSize = 50):
        QGraphicsRectItem.__init__(self, 0, 0, size.width(), size.height(),
                                   parent)
        self.setPos(pos)
        self.newEvent = IsClicked()
        self.newEvent.area = self

        #self.setAcceptedMouseButtons(QtCore.Qt.NoButton)
        self.setFlags(QGraphicsItem.ItemIsMovable |
            QGraphicsItem.ItemIsFocusable |
            QGraphicsItem.ItemIsSelectable)

        ## set index label
        self.text = QGraphicsTextItem("%d" % index, self)
        self.setTextSize(textSize)

        ## TODO: How to create constants for the type?
        ## (such as constants in Qt) (enum?)
        self.kind = type_

        pen = QPen(self.color, areaBorder, Qt.SolidLine,
                   Qt.RoundCap, Qt.RoundJoin)
        self.setPen(pen)
        # self.setAcceptsHoverEvents(True)  # TODO

        # self.text.setFlag(QtGui.QGraphicsItem.ItemIgnoresTransformations)

    def setIndex(self, idx):
        self.text.setPlainText(str(idx))

    def setTextSize(self, size):
        font = QFont()
        font.setPointSizeF(size)
        self.text.setFont(font)

    def contextMenuEvent(self, event):
        menu = QMenu()
        removeAction = menu.addAction(QA.translate('QOcrWidget', "Remove"))
        #Action = menu.addAction(self.scene().tr("Remove"))
        menu.addSeparator()
        textAction = menu.addAction(QA.translate('QOcrWidget', "Text"))
        graphicsAction = menu.addAction(QA.translate('QOcrWidget', "Graphics"))

        ## verification of the type of the selection and
        ## setting a check box near the type that is in use
        textAction.setCheckable(True)
        graphicsAction.setCheckable(True)

        if self.kind == 1:
            textAction.setChecked(True)
        elif self.kind == 2:
            graphicsAction.setChecked(True)

        selectedAction = menu.exec_(event.screenPos())

        if selectedAction == removeAction:
            self.scene().removeArea(self)
        elif selectedAction == textAction:
            self.kind = 1
        elif selectedAction == graphicsAction:
            self.kind = 2

    # when the area is selected the signal "isClicked()" is raised
    def mousePressEvent(self, event):
        self.newEvent.isClicked.emit()
        QGraphicsRectItem.mousePressEvent(self, event)

    # type property
    def _setType(self, type_):
        self.__type = type_

        if self.__type == 1:
            self.color = Qt.darkGreen
        else:  ## TODO: else -> elif ... + else raise exception
            self.color = Qt.blue

        self.text.setDefaultTextColor(self.color)

        pen = self.pen()
        pen.setColor(self.color)
        self.setPen(pen)

    def _type(self):
        return self.__type

    kind = property(fget=_type, fset=_setType)
开发者ID:correosdelbosque,项目名称:lector,代码行数:93,代码来源:ocrarea.py

示例12: MessageItem

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class MessageItem(GraphicsItem):
    def __init__(self, model_item: SimulatorMessage, parent=None):
        assert isinstance(model_item, SimulatorMessage)
        super().__init__(model_item=model_item, parent=parent)

        self.setFlag(QGraphicsItem.ItemIsPanel, True)
        self.arrow = MessageArrowItem(self)

        self.repeat_text = QGraphicsTextItem(self)
        self.repeat_text.setFont(self.font)

    def update_flags(self):
        if self.scene().mode == 0:
            self.set_flags(is_selectable=True, is_movable=True, accept_hover_events=True, accept_drops=True)

    def width(self):
        labels = self.labels()
        width = self.number.boundingRect().width()
        # width += 5
        width += sum([lbl.boundingRect().width() for lbl in labels])
        width += 5 * (len(labels) - 1)
        width += self.repeat_text.boundingRect().width()

        return width

    def refresh(self):
        self.repeat_text.setPlainText("(" + str(self.model_item.repeat) + "x)" if self.model_item.repeat > 1 else "")

    def labels(self):
        self.refresh_unlabeled_range_marker()
        unlabeled_range_items = [uri for uri in self.childItems() if isinstance(uri, UnlabeledRangeItem)]
        result = []

        start = 0
        i = 0

        message = self.model_item

        if len(message) and not message.message_type:
            result.append(unlabeled_range_items[0])
        else:
            for lbl in message.message_type:
                if lbl.start > start:
                    result.append(unlabeled_range_items[i])
                    i += 1

                result.append(self.scene().model_to_scene(lbl))
                start = lbl.end

            if start < len(message):
                result.append(unlabeled_range_items[i])

        return result

    def refresh_unlabeled_range_marker(self):
        msg = self.model_item

        urm = [item for item in self.childItems() if isinstance(item, UnlabeledRangeItem)]

        if len(msg):
            num_unlabeled_ranges = len(msg.message_type.unlabeled_ranges)

            if msg.message_type and msg.message_type[-1].end >= len(msg):
                num_unlabeled_ranges -= 1
        else:
            num_unlabeled_ranges = 0

        if len(urm) < num_unlabeled_ranges:
            for i in range(num_unlabeled_ranges - len(urm)):
                UnlabeledRangeItem(self)
        else:
            for i in range(len(urm) - num_unlabeled_ranges):
                self.scene().removeItem(urm[i])

    def update_position(self, x_pos, y_pos):
        labels = self.labels()
        self.setPos(QPointF(x_pos, y_pos))

        p_source = self.mapFromItem(self.source.line, self.source.line.line().p1())
        p_destination = self.mapFromItem(self.destination.line, self.destination.line.line().p1())

        arrow_width = abs(p_source.x() - p_destination.x())

        start_x = min(p_source.x(), p_destination.x())
        start_x += (arrow_width - self.width()) / 2
        start_y = 0

        self.number.setPos(start_x, start_y)
        start_x += self.number.boundingRect().width()

        for label in labels:
            label.setPos(start_x, start_y)
            start_x += label.boundingRect().width() + 5

        self.repeat_text.setPos(start_x, start_y)

        if labels:
            start_y += labels[0].boundingRect().height() + 5
        else:
            start_y += 26
#.........这里部分代码省略.........
开发者ID:jopohl,项目名称:urh,代码行数:103,代码来源:MessageItem.py

示例13: RuleConditionItem

# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import setFont [as 别名]
class RuleConditionItem(GraphicsItem):
    def __init__(self, model_item: SimulatorRuleCondition, parent=None):
        assert isinstance(model_item, SimulatorRuleCondition)
        super().__init__(model_item=model_item, parent=parent)

        self.number.setFont(self.font_bold)

        self.text = QGraphicsTextItem(self)
        self.text.setPlainText(self.model_item.type.value)
        self.text.setFont(self.font_bold)

        self.desc = QGraphicsTextItem(self)
        self.desc.setFont(self.font)

    def update_flags(self):
        if self.scene().mode == 0:
            self.set_flags(is_selectable=True, accept_hover_events=True, accept_drops=True)
        else:
            self.set_flags(is_selectable=True, accept_hover_events=True)

    def labels_width(self):
        return max(self.number.boundingRect().width() + self.text.boundingRect().width(),
                   self.desc.boundingRect().width())

    def refresh(self):
        if len(self.model_item.condition):
            if len(self.model_item.condition) > 20:
                self.desc.setPlainText(self.model_item.condition[:20] + "...")
            else:
                self.desc.setPlainText(self.model_item.condition)
        elif self.model_item.type != ConditionType.ELSE:
            self.desc.setPlainText("<Condition>")

    def update_position(self, x_pos, y_pos):
        self.setPos(x_pos, y_pos)

        start_y = 0
        start_x = ((self.scene().items_width() + 40) - (
                    self.number.boundingRect().width() + self.text.boundingRect().width())) / 2
        self.number.setPos(start_x, start_y)
        start_x += self.number.boundingRect().width()
        self.text.setPos(start_x, start_y)
        start_y += round(self.number.boundingRect().height())
        start_x = ((self.scene().items_width() + 40) - self.desc.boundingRect().width()) / 2
        self.desc.setPos(start_x, start_y)

        if self.model_item.type != ConditionType.ELSE:
            start_y += round(self.desc.boundingRect().height())

        start_y += 5

        for child in self.get_scene_children():
            child.update_position(20, start_y)
            start_y += round(child.boundingRect().height())

        width = self.scene().items_width()
        self.prepareGeometryChange()
        self.bounding_rect = QRectF(0, 0, width + 40, self.childrenBoundingRect().height() + 5)

    def update_drop_indicator(self, pos):
        rect = self.boundingRect()

        if pos.y() - rect.top() < rect.height() / 3:
            self.drop_indicator_position = QAbstractItemView.AboveItem
        elif rect.bottom() - pos.y() < rect.height() / 3:
            self.drop_indicator_position = QAbstractItemView.BelowItem
        else:
            self.drop_indicator_position = QAbstractItemView.OnItem

        self.update()

    def paint(self, painter, option, widget):
        if self.scene().mode == 1:
            self.setOpacity(1 if self.model_item.logging_active else 0.3)

        painter.setOpacity(constants.SELECTION_OPACITY)

        if self.hover_active or self.isSelected():
            painter.setBrush(constants.SELECTION_COLOR)
        elif not self.is_valid():
            painter.setBrush(QColor(255, 0, 0, 150))
        else:
            painter.setBrush(QColor.fromRgb(204, 204, 204, 255))

        height = self.number.boundingRect().height()

        if self.model_item.type != ConditionType.ELSE:
            height += self.desc.boundingRect().height()

        painter.drawRect(QRectF(0, 0, self.boundingRect().width(), height))

        painter.setBrush(Qt.NoBrush)
        painter.drawRect(self.boundingRect())

        if self.drag_over:
            self.paint_drop_indicator(painter)

    def paint_drop_indicator(self, painter):
        painter.setPen(QPen(Qt.darkRed, 2, Qt.SolidLine))
        painter.setBrush(Qt.NoBrush)
#.........这里部分代码省略.........
开发者ID:jopohl,项目名称:urh,代码行数:103,代码来源:RuleItem.py


注:本文中的PyQt5.QtWidgets.QGraphicsTextItem.setFont方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。