def update(self, _pageFormat, _mmPageMargins=QMarginsF()): self.m_pageFormat = _pageFormat self.m_mmPageSize = QPageSize(self.m_pageFormat).rect(QPageSize.Millimeter).size() self.m_mmPageMargins = _mmPageMargins # Calculate values in pixels x = True; y = False self.m_pxPageSize = QSizeF(self.mmToPx(self.m_mmPageSize.width(), x), self.mmToPx(self.m_mmPageSize.height(), y)) self.m_pxPageMargins = QMarginsF(self.mmToPx(self.m_mmPageMargins.left(), x), self.mmToPx(self.m_mmPageMargins.top(), y), self.mmToPx(self.m_mmPageMargins.right(), x), self.mmToPx(self.m_mmPageMargins.bottom(), y))
def paint(self, painter, *args, **kwargs): if self.hovered: margin = QMarginsF(7, 5, 7, 5) else: margin = QMarginsF(3, 0, 3, 0) box = self.boundingRect().marginsAdded(margin) path = QPainterPath() path.addRoundedRect(box, 5, 5) painter.fillPath(path, self.background_color) super().paint(painter, *args, **kwargs)
def __init__(self, page_width, page_height, crop_margin_width=0 * mm): self.page_width = page_width self.page_height = page_height self.margin_width = crop_margin_width self.include_crop_marks = bool(crop_margin_width) QApplication(['my-q-application']) f = QFontDatabase.addApplicationFont( '../../fonts/OldStandard-Regular.ttf') f = QFontDatabase.addApplicationFont('OldStandard-Italic.ttf') f = QFontDatabase.addApplicationFont('OldStandard-Bold.ttf') f = QFontDatabase.addApplicationFont('fonts/Inconsolata-Regular.ttf') f = QFontDatabase.addApplicationFont('fonts/UbuntuMono-R.ttf') f = QFontDatabase.addApplicationFont('../../fonts/GenBasB.ttf') f = QFontDatabase.addApplicationFont('../../fonts/GenBasR.ttf') #f = QFontDatabase.addApplicationFont('../../fonts/Inconsolata-Regular.ttf') # print(f) names = QFontDatabase.applicationFontFamilies(f) # print(names) self.writer = QPdfWriter('book.pdf') size = QSizeF(as_mm(2 * crop_margin_width + page_width), as_mm(2 * crop_margin_width + page_height)) print(size) self.writer.setPageSizeMM(size) margins = QMarginsF(as_mm(crop_margin_width), as_mm(crop_margin_width), as_mm(crop_margin_width), as_mm(crop_margin_width)) print(margins) self.writer.setPageMargins(margins, QPageLayout.Millimeter) self.painter = QPainter(self.writer) if self.include_crop_marks: self.draw_crop_marks()
def boundingRect(self): box = self.rect() viewBox = self.mapRectFromScene(box) margin = QMarginsF(*([self.penWidth] * 4)) viewBox += margin box = self.mapRectToScene(viewBox) return box
def print_pdf(page: QWebEngineView, filename): page.page().printToPdf( filename, QPageLayout(QPageSize(QPageSize.A4), QPageLayout.Portrait, QMarginsF(5 * mm, 5 * mm, 5 * mm, 5 * mm))) page.page().pdfPrintingFinished.connect( lambda file_path, success: app.quit())
def save_image_to(self, path, top_margin=50, bottom_margin=50, left_margin=50, right_margin=50): margins = QMarginsF(left_margin, top_margin, right_margin, bottom_margin) oldRect = self.scene().sceneRect() minRect = self.scene().itemsBoundingRect() imgRect = minRect.marginsAdded(margins) image = QImage(imgRect.size().toSize(), QImage.Format_ARGB32) image.fill(Qt.white) painter = QPainter(image) painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.HighQualityAntialiasing) # draw the image self.scene().setSceneRect(imgRect) self.scene().render(painter) image.save(path) # cleanup painter.end() # restore the old scene rect self.scene().setSceneRect(oldRect)
def paint(self, painter, *args, **kwargs): margin = QMarginsF(3, 0, 3, 0) box = self.boundingRect().marginsAdded(margin) path = QPainterPath() path.addRoundedRect(box, 5, 5) painter.fillPath(path, QColor(*self.background_color)) super().paint(painter, *args, **kwargs)
def _boundingRect(self): bounding_rect = self.childrenBoundingRect().marginsAdded(self.margins) if self.qblock_annotations: # Hack to keep the arrows centered on the graph blocks. hack_right_margin = QMarginsF(0, 0, self.qblock_annotations.width, 0) return bounding_rect.marginsAdded(hack_right_margin) return bounding_rect
def paintPageNumbers(self): # Page numbers are drawn only when the editor is in page mode, # if fields are set and the option to display numbers is enabled if (self.m_usePageMode and not self.m_pageMetrics.pxPageMargins().isNull() and self.m_showPageNumbers): pageWidth = self.m_pageMetrics.pxPageSize().width() pageHeight = self.m_pageMetrics.pxPageSize().height() pageMargins = QMarginsF(self.m_pageMetrics.pxPageMargins()) p = QPainter(self.viewport()) font = QFont() font.setPointSize(10) font.setFamily('Calibri') p.setFont(font) p.setPen(QPen(self.palette().text(), 1)) # The current height and width are displayed on the screen. curHeight = pageHeight - (self.verticalScrollBar().value() % pageHeight) # The start of the field must take into account the scrollbar offset. leftMarginPosition = pageMargins.left() - self.horizontalScrollBar( ).value() # Total field width marginWidth = pageWidth - pageMargins.left() - pageMargins.right() # The number of the first page to see. pageNumber = self.verticalScrollBar().value() / pageHeight + 1 # Add 0.3 to pageNumber before emitting # to announce page when it is about halfway up the screen self.pageInfo.emit( (int(pageNumber + 0.3), int(self.verticalScrollBar().maximum() / pageHeight + 1))) # Paint page numbers while there are remotely more visible pages while (curHeight < pageHeight + self.height()): # Define the space for top page number; paint number topMarginRect = QRectF(leftMarginPosition, curHeight - pageHeight, marginWidth, pageMargins.top()) self.paintPageNumber(p, topMarginRect, True, pageNumber) # Define the space for bottom page number; paint number bottomMarginRect = QRectF(leftMarginPosition, curHeight - pageMargins.bottom(), marginWidth, pageMargins.bottom()) self.paintPageNumber(p, bottomMarginRect, False, pageNumber) # Go to next page pageNumber += 1 curHeight += pageHeight
def testWrite(self): temporaryFile = QTemporaryFile(QDir.tempPath() + "/pdfwriter_test_XXXXXX.pdf") self.assertTrue(temporaryFile.open()) pdfWriter = QPdfWriter(temporaryFile) pdfWriter.setPageLayout( QPageLayout(QPageSize(QPageSize.A4), QPageLayout.Portrait, QMarginsF(10, 10, 10, 10))) doc = QTextDocument("Some text") doc.print_(pdfWriter) temporaryFile.close() self.assertTrue(temporaryFile.size() > 0)
def shrink_if_needed(self): """Shrinks the scene rectangle if it is considerably larger than the area occupied by items.""" items_rect = self.itemsBoundingRect() # Margins from initial Design View scene size. # We don't want to shrink the scene immediately when user moves an item on a fresh scene. margins = QMarginsF(self._horizontal_threshold, self._vertical_threshold, self._horizontal_threshold, self._vertical_threshold) acceptable_items_rect = items_rect.marginsAdded(margins) scene_rect = self.sceneRect() if not acceptable_items_rect.contains(scene_rect): self.setSceneRect(acceptable_items_rect.intersected(scene_rect))
def redo(self): self.tabWidget.setCurrentIndex(self.tabIndex) self.tabWidget.getTableView(self.tabIndex).clearSelection() model = self.tabWidget.getCurrentTableModel() cellIndex = model.index(self.row, self.col) self.tabWidget.setCurrentSelectedCell(cellIndex) page = model.pageAtIndex(cellIndex) if page != self.page: filename = self.tabWidget.widget(self.tabIndex).filename pattern = os.path.join(os.path.dirname(filename), "**", page + ".*") possibleNames = glob.glob(pattern, recursive=True) imageName = None for name in possibleNames: mtypes = mimetypes.guess_type(name) if isinstance(mtypes[0], str) and 'image' in mtypes[0]: imageName = name break if not imageName: self.messageLabel.setText(f"{page} image not found") return self.graphicsScene.removeAllItems() pixmap = QPixmap(imageName) self.graphicsScene.setPage(page, pixmap) if page != self.page or self.tabIndex != self.prevTabIndex: self.graphicsScene.removeAllBoxes() for tabIndex, pageData in enumerate( self.tabWidget.pageDatas(page)): tabName = self.tabWidget.tabText(tabIndex) for rowIndex, rowData in pageData.iterrows(): label = rowData["label"] color = self.tabWidget.color_map(tabIndex)[label] self.graphicsScene.addBox( tabIndex, tabName, rowIndex, page, label, rowData["box"], color) box = self.graphicsScene.box(self.tabIndex, self.row) boundingRect = box.boundingRect() margin_size = min(boundingRect.width(), boundingRect.height()) * 2 margin = QMarginsF(*([margin_size] * 4)) viewRect = boundingRect + margin self.graphicsView.fitInView(viewRect, Qt.KeepAspectRatio) self.graphicsView.setFocus() self.comboBox.blockSignals(True) self.comboBox.setCurrentText(box.label) self.comboBox.setCurrentIndex(self.comboBox.findText(self.label)) self.comboBox.blockSignals(False) self.setText(f"clicked row {self.tabIndex}:{self.row}")
def export(self, filename): self.printer = QPrinter() self.printer.setOutputFormat(QPrinter.PdfFormat) self.printer.setOutputFileName(filename) self.printer.setPageMargins(QMarginsF(0, 0, 0, 0)) self.printer.setResolution(96) self.printer.setFullPage(True) pages = self.document['pages'] if pages: page = pages[0] self.printer.setPageSizeMM(QSizeF(page.width / mm, page.height / mm)) self.painter = QPainter() self.painter.begin(self.printer) self._isFirstPage = True for page in pages: self.exportPage(page) self._isFirstPage = False self.painter.end()
def __init__(self, workspace, func_addr, disasm_view, disasm, infodock, addr, cfg_nodes, out_branches, scene, parent=None, container=None): super().__init__(parent=parent, container=container) # initialization self.workspace = workspace self.func_addr = func_addr self.disasm_view = disasm_view self.disasm = disasm self.infodock = infodock self.variable_manager = infodock.variable_manager self.addr = addr self.cfg_nodes = cfg_nodes self.out_branches = out_branches self._scene = scene self.margins = QMarginsF(self.LEFT_PADDING, self.TOP_PADDING, self.RIGHT_PADDING, self.BOTTOM_PADDING) self._config = Conf self.objects = [] # instructions and labels self._block_item = None # type: QPainterPath self._block_item_obj = None # type: QGraphicsPathItem self.qblock_annotations = None self.addr_to_insns = {} self.addr_to_labels = {} self._init_widgets() self._objects_are_hidden = False self._create_block_item() self.setAcceptHoverEvents(True)
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()
def _generate_hover_region(self): """ Paint the memory region indicator. """ if self._map_hover_region_item: self.scene().removeItem(self._map_hover_region_item) self._map_hover_region_item = None mr = self._map_hover_region if mr is None: return pw = 1.0 hpw = pw / 2 pen = QPen(Qt.red) pen.setWidth(pw) r = self._get_region_rect(mr) r = r.marginsRemoved(QMarginsF(hpw, hpw, hpw, hpw)) item = QGraphicsRectItem(r, parent=self) item.setPen(pen) item.setZValue(self.ZVALUE_HOVER) self._map_hover_region_item = item
def on_actionSave_Document_triggered(self): print("on_actionSave_Document_triggered") ui = self.ui fileName = "./q_text-document-integration.pdf" #fileName = QFileDialog.getSaveFileName(self, "Save document...", qApp.applicationDirPath(), "*.pdf", None) #if fileName == None: # print("No file") # return #fileName = fileName[0]+".pdf" print("FILENAMKE=", fileName) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fileName) pageMargins = QMargins(20, 20, 20, 20) pageLayout = QPageLayout() pageLayout.setMode(QPageLayout.StandardMode) pageLayout.setOrientation(QPageLayout.Portrait) pageLayout.setPageSize(QPageSize(QPageSize.A4)) pageLayout.setUnits(QPageLayout.Millimeter) pageLayout.setMargins(QMarginsF(pageMargins)) printer.setPageLayout(pageLayout) ui.textEdit.document().setPageSize(printer.pageRect().size()) ui.textEdit.document().print_(printer)
def boundingRect(self): half_pen_width = self.PEN_WIDTH / 2 margins = QMarginsF(half_pen_width, half_pen_width, half_pen_width, half_pen_width) return self._scene_rect.marginsAdded(margins)
def _pin_pos(rect, x, y): margins = (_EXT_LENGTH, ) * 4 rect = rect.marginsAdded(QMarginsF(*margins)) return QPointF(rect.x() + rect.width() * x - Pin._SIZE.width() / 2, rect.y() + rect.height() * y - Pin._SIZE.height() / 2)
class PageMetrics(): m_pageFormat = QPageSize.PageSizeId() m_mmPageSize = QSizeF() m_mmPageMargins = QMarginsF() m_pxPageSize = QSizeF() m_pxPageMargins = QMarginsF() def __init__(self): super(PageMetrics, self).__init__() def mmToInches(self, mm): return mm * 0.039370147 def mmToPx(self, _mm, _x): return self.mmToInches(_mm) * (qApp.desktop().logicalDpiX() if _x else qApp.desktop().logicalDpiY()) def pageSizeIdFromString(self, _from): result = QPageSize.A4 if (_from == "A0"): result = QPageSize.A0 elif (_from == "A1"): result = QPageSize.A1 elif (_from == "A2"): result = QPageSize.A2 elif (_from == "A3"): result = QPageSize.A3 elif (_from == "A4"): result = QPageSize.A4 elif (_from == "A5"): result = QPageSize.A5 elif (_from == "A6"): result = QPageSize.A6 else: Q_ASSERT_X(0, Q_FUNC_INFO, qPrintable("Undefined page size: " + _from)) return result def stringFromPageSizeId(self, _pageSize): result = "" if(_pageSize == QPageSize.A0): result = "A0" elif (_pageSize == QPageSize.A1): result = "A1" elif (_pageSize == QPageSize.A2): result = "A2" elif (_pageSize == QPageSize.A3): result = "A3" elif (_pageSize == QPageSize.A4): result = "A4" elif (_pageSize == QPageSize.A5): result = "A5" elif (_pageSize == QPageSize.A6): result = "A6" else: Q_ASSERT_X(0, Q_FUNC_INFO, qPrintable("Undefined page size: " + QString.number(_pageSize))) return result def update(self, _pageFormat, _mmPageMargins=QMarginsF()): self.m_pageFormat = _pageFormat self.m_mmPageSize = QPageSize(self.m_pageFormat).rect(QPageSize.Millimeter).size() self.m_mmPageMargins = _mmPageMargins # Calculate values in pixels x = True; y = False self.m_pxPageSize = QSizeF(self.mmToPx(self.m_mmPageSize.width(), x), self.mmToPx(self.m_mmPageSize.height(), y)) self.m_pxPageMargins = QMarginsF(self.mmToPx(self.m_mmPageMargins.left(), x), self.mmToPx(self.m_mmPageMargins.top(), y), self.mmToPx(self.m_mmPageMargins.right(), x), self.mmToPx(self.m_mmPageMargins.bottom(), y)) def pageFormat(self): return self.m_pageFormat def mmPageSize(self): return self.m_mmPageSize def mmPageMargins(self): return self.m_mmPageMargins def pxPageSize(self): return QSizeF(self.m_pxPageSize.width(), self.m_pxPageSize.height()) def pxPageMargins(self): return QMarginsF(self.m_pxPageMargins.left(), self.m_pxPageMargins.top(), self.m_pxPageMargins.right(), self.m_pxPageMargins.bottom())
def pxPageMargins(self): return QMarginsF(self.m_pxPageMargins.left(), self.m_pxPageMargins.top(), self.m_pxPageMargins.right(), self.m_pxPageMargins.bottom())
def _boundingRect(self): cbr = self.childrenBoundingRect() margins = QMarginsF(self.LEFT_PADDING, self.TOP_PADDING, self.RIGHT_PADDING, self.BOTTOM_PADDING) return cbr.marginsAdded(margins)
def __init__(self, fileName=None): super(MainWindow, self).__init__() self.curFile = '' self.curPage = ( 0, 0 ) # Tuple containing current page and total pages of the current file self.setWindowTitle('Pablo Editor') self.setWindowIcon(QIcon( GenUtils.resource_path('src/images/icon.ico'))) self.setWindowState(Qt.WindowFullScreen) self.setWindowState(Qt.WindowMaximized) # available_geometry = app.desktop().availableGeometry(self) # self.resize(available_geometry.width(), available_geometry.height()) self.readSettings() self.dropView = dropview.DropView() self.paged_text_edit = pagedtextedit.PagedTextEdit(self.dropView) # The textedit must be transparent; the white pages are painted in paintEvent() function self.paged_text_edit.setStyleSheet( "QTextEdit { background-color: transparent }") self.paged_text_edit.setFrameStyle( QFrame.NoFrame) # Removes a border-like line around the TextEdit doc = QTextDocument() font = QFont() font.setPointSize(12) font.setFamily('Calibri') doc.setDefaultFont(font) # doc.setDefaultStyleSheet("body { font-color: black; font-family: Calibri; font-size: 12;} ") self.paged_text_edit.setDocument(doc) self.paged_text_edit.setPageFormat(QPageSize.A5Extra) self.paged_text_edit.setPageMargins(QMarginsF(15, 15, 15, 15)) self.paged_text_edit.setUsePageMode(True) self.paged_text_edit.setPageNumbersAlignment(Qt.AlignBottom | Qt.AlignCenter) self.text_edit_layout = QHBoxLayout() self.text_edit_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.text_edit_layout.setMargin(0) self.paged_text_edit.setLayout(self.text_edit_layout) # This below block of code prevents undoing the setDocumentMargin() and setFrameformat() # methods in the aboutUpdateDocumentGeometry function self.paged_text_edit.aboutUpdateDocumentGeometry() # self.paged_text_edit.document().clearUndoRedoStack() # this does not work # These commands work self.paged_text_edit.document().setUndoRedoEnabled(False) self.paged_text_edit.document().setUndoRedoEnabled(True) self.setCentralWidget(self.dropView) self.dropView.addWidget(self.paged_text_edit) self.dropView.setCurrentWidget(self.paged_text_edit) self._setup_components() self.setCurrentFile('') self.paged_text_edit.document().contentsChanged.connect( self.documentWasModified) self.paged_text_edit.currentCharFormatChanged.connect( self.updateFontWidgets) self.paged_text_edit.cursorPositionChanged.connect( self.updatePositions) self.paged_text_edit.pageInfo.connect(self.readPageInfo) self.statusBar.writeMessageOnStatus("Ready", 10000)
def __init__(self, path): self.painter = None self.writer = QPdfWriter(path) margins = QMarginsF(0, 0, 0, 0) self.writer.setPageMargins(margins, QPageLayout.Millimeter)