本文整理汇总了Python中PyQt5.QtWidgets.QGraphicsTextItem.boundingRect方法的典型用法代码示例。如果您正苦于以下问题:Python QGraphicsTextItem.boundingRect方法的具体用法?Python QGraphicsTextItem.boundingRect怎么用?Python QGraphicsTextItem.boundingRect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QGraphicsTextItem
的用法示例。
在下文中一共展示了QGraphicsTextItem.boundingRect方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createImage
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [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
示例2: ActionItem
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [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
示例3: ParticipantItem
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [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
示例4: Edge
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [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])
示例5: QGraphicsScene
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [as 别名]
textItem.setHtml(
'<font color="white"><b>Stickman</b>'
"<p>"
"Tell the stickman what to do!"
"</p>"
"<p><i>"
'<li>Press <font color="purple">J</font> to make the stickman jump.</li>'
'<li>Press <font color="purple">D</font> to make the stickman dance.</li>'
'<li>Press <font color="purple">C</font> to make him chill out.</li>'
'<li>When you are done, press <font color="purple">Escape</font>.</li>'
"</i></p>"
"<p>If he is unlucky, the stickman will get struck by lightning, and never jump, dance or chill out again."
"</p></font>"
)
w = textItem.boundingRect().width()
stickManBoundingRect = stickMan.mapToScene(stickMan.boundingRect()).boundingRect()
textItem.setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0)
scene = QGraphicsScene()
scene.addItem(stickMan)
scene.addItem(textItem)
scene.setBackgroundBrush(Qt.black)
view = GraphicsView()
view.setRenderHints(QPainter.Antialiasing)
view.setTransformationAnchor(QGraphicsView.NoAnchor)
view.setScene(scene)
view.show()
view.setFocus()
示例6: MessageItem
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [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
#.........这里部分代码省略.........
示例7: RuleConditionItem
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [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)
#.........这里部分代码省略.........
示例8: Node
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsTextItem [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsTextItem import boundingRect [as 别名]
#.........这里部分代码省略.........
beziercpy = self.bezier[:]
for bezier in beziercpy:
bezier.iostart.bezier.remove(bezier)
bezier.ioend.bezier.remove(bezier)
self.parent.parent.scene.removeItem(bezier)
def __init__(self, parent, nodedata=None, id=None):
if nodedata is None:
raise ValueError("Nodetype must not be 'None'")
self.nodedata = nodedata
self.parent = parent
self.width = 32
self.height = 0
super().__init__(-self.width / 2, -self.height / 2, self.width, self.height)
self.setAcceptHoverEvents(True)
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.extraNodeData = {}
if id is not None:
self.id = id
else:
self.id = uuid.uuid4().hex # Random ID to identify node
self.nodebrush = QBrush(QColor(100, 100, 100, 255))
self.setBrush(self.nodebrush)
# Node Title
self.nodetitle = self.nodedata.name
self.nodetitleTextItem = QGraphicsTextItem(self.nodetitle, self)
self.width = max(self.width, self.nodetitleTextItem.boundingRect().width())
self.height += self.nodetitleTextItem.boundingRect().height()
# Create all the text items for the IO
self.inputTextItems = []
self.outputTextItems = []
for i in range(max(len(self.nodedata.inputDefs), len(self.nodedata.outputDefs))):
linewidth = 0
lineheight = 0
try:
self.inputTextItems.append(QGraphicsTextItem(self.nodedata.inputDefs[i][0], self))
linewidth += self.inputTextItems[i].boundingRect().width()
lineheight = max(lineheight, self.inputTextItems[i].boundingRect().height())
except IndexError:
pass
try:
self.outputTextItems.append(QGraphicsTextItem(self.nodedata.outputDefs[i][0], self))
linewidth += self.outputTextItems[i].boundingRect().width()
lineheight = max(lineheight, self.outputTextItems[i].boundingRect().height())
except IndexError:
pass
linewidth += 12 # Keep atleast 12px distance between the input and output text
self.width = max(self.width, linewidth)
self.height += lineheight
# Set correct positions for all text items
self.nodetitleTextItem.setPos(-self.width / 2, -self.height / 2)
self.inputIO = []
heightPointer = 0
for i in range(max(len(self.nodedata.inputDefs), len(self.nodedata.outputDefs))):