def qrect_aligned_to( rect_a: QRectF, rect_b: QRectF, alignment: Qt.Alignment) -> QRectF: res = QRectF(rect_a) valign = alignment & Qt.AlignVertical_Mask halign = alignment & Qt.AlignHorizontal_Mask if valign == Qt.AlignTop: res.moveTop(rect_b.top()) if valign == Qt.AlignVCenter: res.moveCenter(QPointF(res.center().x(), rect_b.center().y())) if valign == Qt.AlignBottom: res.moveBottom(rect_b.bottom()) if halign == Qt.AlignLeft: res.moveLeft(rect_b.left()) if halign == Qt.AlignHCenter: res.moveCenter(QPointF(rect_b.center().x(), res.center().y())) if halign == Qt.AlignRight: res.moveRight(rect_b.right()) return res
def grab_svg(scene): # type: (QGraphicsScene) -> str """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ svg_buffer = QBuffer() gen = _QSvgGenerator() gen.setOutputDevice(svg_buffer) items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10) if items_rect.isNull(): items_rect = QRectF(0, 0, 10, 10) width, height = items_rect.width(), items_rect.height() rect_ratio = float(width) / height # Keep a fixed aspect ratio. aspect_ratio = 1.618 if rect_ratio > aspect_ratio: height = int(height * rect_ratio / aspect_ratio) else: width = int(width * aspect_ratio / rect_ratio) target_rect = QRectF(0, 0, width, height) source_rect = QRectF(0, 0, width, height) source_rect.moveCenter(items_rect.center()) gen.setSize(target_rect.size().toSize()) gen.setViewBox(target_rect) painter = QPainter(gen) # Draw background. painter.setPen(Qt.NoPen) painter.setBrush(scene.palette().base()) painter.drawRect(target_rect) # Render the scene scene.render(painter, target_rect, source_rect) painter.end() buffer_str = bytes(svg_buffer.buffer()) return buffer_str.decode("utf-8")
def grab_svg(scene): """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ from AnyQt.QtSvg import QSvgGenerator svg_buffer = QBuffer() gen = QSvgGenerator() gen.setOutputDevice(svg_buffer) items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10) if items_rect.isNull(): items_rect = QRectF(0, 0, 10, 10) width, height = items_rect.width(), items_rect.height() rect_ratio = float(width) / height # Keep a fixed aspect ratio. aspect_ratio = 1.618 if rect_ratio > aspect_ratio: height = int(height * rect_ratio / aspect_ratio) else: width = int(width * aspect_ratio / rect_ratio) target_rect = QRectF(0, 0, width, height) source_rect = QRectF(0, 0, width, height) source_rect.moveCenter(items_rect.center()) gen.setSize(target_rect.size().toSize()) gen.setViewBox(target_rect) painter = QPainter(gen) # Draw background. painter.setBrush(QBrush(Qt.white)) painter.drawRect(target_rect) # Render the scene scene.render(painter, target_rect, source_rect) painter.end() buffer_str = bytes(svg_buffer.buffer()) return buffer_str.decode("utf-8")