def __init__(self, parent=None): super(ProgramaImpressor, self).__init__(parent) rotuloNome = QtWidgets.QLabel("Nome: ") rotuloEndereco = QtWidgets.QLabel(u"Endereço: ") rotuloOutros = QtWidgets.QLabel("Diversos: ") self.impressor = QtPrintSupport.QPrinter() self.txtnome = QtWidgets.QLineEdit() self.txtendereco = QtWidgets.QLineEdit() self.txtdiversos = QtWidgets.QTextEdit() self.btnimprimir = QtWidgets.QPushButton("&Imprimir") layoutHorizontal = QtWidgets.QHBoxLayout() layoutHorizontal2 = QtWidgets.QHBoxLayout() layoutHorizontal3 = QtWidgets.QHBoxLayout() layoutVertical = QtWidgets.QVBoxLayout() layoutHorizontal.addWidget(rotuloNome) layoutHorizontal.addWidget(self.txtnome) layoutHorizontal2.addWidget(rotuloEndereco) layoutHorizontal2.addWidget(self.txtendereco) layoutHorizontal3.addWidget(rotuloOutros) layoutHorizontal3.addWidget(self.txtdiversos) layoutVertical.addLayout(layoutHorizontal) layoutVertical.addLayout(layoutHorizontal2) layoutVertical.addLayout(layoutHorizontal3) layoutVertical.addWidget(self.btnimprimir) self.setLayout(layoutVertical) self.dialogo = QtPrintSupport.QPrintPreviewDialog() self.html = u"" self.documento = QWebEngineView() self.dialogo.paintRequested.connect(self.documento.print_) self.documento.loadFinished['bool'].connect(self.previaImpressao) self.btnimprimir.clicked.connect(self.imprimir)
def __init__(self, parent=None): # Constructor of the class. super(UApp, self).__init__(parent) # Initialization of the class. UTools.__init__(self) # Initialization of the tools # print self.us1 # class with functions. self.frame1 = UFrame(self.twid3) # Create the first frame with self.frame1.setLineWidth(3) # parent as third widget. self.frame1.setFrameStyle(6) # Styled panel frame style. self.table = UTabView(self.frame1) # Creation of the table with self.table.setVisible(False) # parent as frame 1 and gets model = UTModel() # data from the model. self.table.setModel(model) # Set model data to the table. self.text_edit = UTextEd(self.frame1) # Text Edit field with self.layfr1 = QtWidgets.QGridLayout() # parent - the first frame. self.layfr1.addWidget(self.table, 0, 0, 1, 1) self.layfr1.addWidget(self.text_edit, 0, 0, 1, 1) self.layfr1.setContentsMargins(0, 0, 0, 0) self.frame1.setLayout(self.layfr1) # layout for this field. self.frame2 = UFrame(self.twid3) # Second frame with parent. self.frame2.setLineWidth(3) # Sets line width of the frame self.frame2.setFrameStyle(0) # and 0 - style No frame. self.frame2.setMaximumWidth(int(self.width()/3)) self.label1 = ULabel(self.frame2) # Label in the second frame. self.label1.setText("User Information") self.label1.setAlignment(QtCore.Qt.AlignCenter) self.combox1 = UComBox(self.frame2) # Adding the combo box. self.combox1.addItems(["Texts", "Table"]) self.combox1.setView(UListV()) # Combo box popup view. self.line_ed1 = ULineEd(self.frame2) # First line edit field. self.line_ed1.setPlaceholderText("Full Name...") self.line_ed2 = ULineEd(self.frame2) # Second that for user email. self.line_ed2.setPlaceholderText("Email...") self.line_ed3 = ULineEd(self.frame2) # Third field for input passw. self.line_ed3.setPlaceholderText("Password...") self.line_ed3.setEchoMode(QtWidgets.QLineEdit.Password) self.push_but1 = UBut1(self.frame2) # Adding the button with text. self.push_but1.setText("Ok") # Adding progress bar with self.progress1 = UProgress(self.frame2) self.progress1.setRange(0, 0) # range (indeterminate mode). self.layfr2_1 = QtWidgets.QGridLayout() self.layfr2_1.addWidget(self.push_but1, 0, 1, 1, 1) self.layfr2_1.addWidget(self.progress1, 1, 0, 1, 2) self.layfr2_1.setSpacing(3) # Spacing for layout - 3 pix. self.layfr2 = QtWidgets.QGridLayout() # Layout for second frame. self.layfr2.addWidget(self.combox1, 0, 0, 1, 1) self.layfr2.addWidget(self.label1, 1, 0, 1, 1) self.layfr2.addWidget(self.line_ed1, 2, 0, 1, 1) self.layfr2.addWidget(self.line_ed2, 3, 0, 1, 1) self.layfr2.addWidget(self.line_ed3, 4, 0, 1, 1) self.layfr2.addLayout(self.layfr2_1, 5, 0, 1, 1) self.layfr2.setSpacing(3) # Sets spacing - 3 pixels. self.layfr2.setContentsMargins(3, 3, 3, 3) self.frame2.setLayout(self.layfr2) # Layout added to frame. self.lay1 = QtWidgets.QGridLayout() # Layout for third widget. self.lay1.addWidget(self.frame1, 0, 0, 1, 1) self.lay1.addWidget(self.frame2, 0, 1, 1, 1) self.twid3.setLayout(self.lay1) # Set layout to the widget. self.mb1.triggered.connect(self.files) self.mb3.triggered.connect(self.options) self.combox1.activated.connect(self.txt_table) self.print_device = QtPrintSupport.QPrinter()
def previaImpressao(self, arg): self.printer = QtPrintSupport.QPrinter() self.dialogo = QtPrintSupport.QPrintDialog(self.printer) # self.dialogo.paintRequested.connect(self.documento.print_) if self.dialogo.exec_() == True: self.documento.print(self.printer, self.okPrinter)
def __init__(self, parent=None): super(ProgramaImpressor, self).__init__(parent) rotuloNome = QtWidgets.QLabel("Nome: ") rotuloEndereco = QtWidgets.QLabel(u"Endereço: ") rotuloOutros = QtWidgets.QLabel("Diversos: ") self.impressor = QtPrintSupport.QPrinter() self.txtnome = QtWidgets.QLineEdit() self.txtendereco = QtWidgets.QLineEdit() self.txtdiversos = QtWidgets.QTextEdit() self.btnimprimir = QtWidgets.QPushButton("&Imprimir") layoutHorizontal = QtWidgets.QHBoxLayout() layoutHorizontal2 = QtWidgets.QHBoxLayout() layoutHorizontal3 = QtWidgets.QHBoxLayout() layoutVertical = QtWidgets.QVBoxLayout() layoutHorizontal.addWidget(rotuloNome) layoutHorizontal.addWidget(self.txtnome) layoutHorizontal2.addWidget(rotuloEndereco) layoutHorizontal2.addWidget(self.txtendereco) layoutHorizontal3.addWidget(rotuloOutros) layoutHorizontal3.addWidget(self.txtdiversos) layoutVertical.addLayout(layoutHorizontal) layoutVertical.addLayout(layoutHorizontal2) layoutVertical.addLayout(layoutHorizontal3) layoutVertical.addWidget(self.btnimprimir) self.setLayout(layoutVertical) self.btnimprimir.clicked.connect(self.imprimir)
def printPreview(ui): printer = QtPrintSupport.QPrinter() dialog = QtPrintSupport.QPrintPreviewDialog(printer) dialog.paintRequested.connect(lambda:print(printer,ui)) if( dialog.exec() == 0 ): return False else: return True
def print_form(self): """ """ if confirm_("Print Screen:"): printer = P.QPrinter() painter = P.G.QPainter() painter.begin(printer) screen = self.grab() # to print whole window painter.drawPixmap(10, 10, screen) painter.end()
def Print(ui): printer = QtPrintSupport.QPrinter() dialog = QtPrintSupport.QPrintDialog(printer) if( dialog.exec() == 0 ): return False else: widget = ui.mdViewer.document() widget.print_(printer) return True
def save_pdf(self, path, dpi=200): cmax = 4 self.view.progress.update_state(text="Rendering...", value=1, maximum=cmax) if self.view.progress.cancel_pressed(): return self.scene().clearSelection() scale = self.get_scale() scale_tgt = SCALE_CUTOFF * 2 if scale < scale_tgt: self.scale_view(scale_tgt / scale) rect = self.scene().itemsBoundingRect() m = min(rect.width(), rect.height()) * 0.05 rect = rect.marginsAdded(QtCore.QMarginsF(m, m, m, m)) w, h = rect.width(), rect.height() self.view.progress.update_state(text="Rendering...", value=2, maximum=cmax) if self.view.progress.cancel_pressed(): return printer = QtPrintSupport.QPrinter() printer.setWinPageSize(QtGui.QPageSize.A4) printer.setFullPage(True) printer.setOrientation(QtPrintSupport.QPrinter.Landscape) printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setOutputFileName(path) size = printer.pageLayout().pageSize().sizePoints() pw, ph = size.height(), size.width() scale = min(pw / w, ph / h) printer.setResolution(int(round(dpi / scale))) ph = int(round(h * (pw / w))) printer.setPageSize( QtGui.QPageSize(QtCore.QSize(ph, pw), units=QtGui.QPageSize.Point)) painter = QtGui.QPainter(printer) self.view.progress.update_state(text="Rendering...", value=3, maximum=cmax) if self.view.progress.cancel_pressed(): painter.end() os.remove(path) return self.scene().render(painter, source=rect) painter.end() self.view.progress.update_state(text="Rendering...", value=4, maximum=cmax)
def select_printer(self): try: printer = QtPrintSupport.QPrinter() pd = QPrintDialog(printer) pd.setOption(QAbstractPrintDialog.PrintSelection) pd.exec_() return printer.printerName() except Exception as e: logging.error(str(e)) return None
def printFile(self): editor = self.letters.currentWidget() printer = QtPrintSupport.QPrinter() dialog = QtPrintSupport.QPrintDialog(printer, self) dialog.setWindowTitle("Print Document") if editor.textCursor().hasSelection(): dialog.addEnabledOption(QtPrintSupport.QAbstractPrintDialog.PrintSelection) if dialog.exec_() != QtWidgets.QDialog.Accepted: return editor.print_(printer)
def _print(self): """ 打印信件函数 :return: """ document = self.textEdit.document() printer = QtPrintSupport.QPrinter() dlg = QtPrintSupport.QPrintDialog(printer, self) if dlg.exec_() != QtWidgets.QDialog.Accepted: return document.print_(printer) self.statusBar().showMessage("Ready", 2000)
def save_as_pdf(self): filename = QFileDialog.getSaveFileName( self, ("Save "), os.path.join(self.selected_save_path, "./new.pdf"), ("PDF (*.pdf)"), )[0] if filename: self.selected_save_path = filename printer = QtPrintSupport.QPrinter( QtPrintSupport.QPrinter.HighResolution) printer.setPageSize(QtPrintSupport.QPrinter.A4) printer.setColorMode(QtPrintSupport.QPrinter.Color) printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setOutputFileName(filename) self.ui.textBrowser.document().print_(printer)
def save_pdf(self, path, dpi=72): self.scene().clearSelection() scale = self.get_scale() rect = self.scene().itemsBoundingRect() m = min(rect.width(), rect.height()) * 0.05 rect = rect.marginsAdded(QtCore.QMarginsF(m, m, m, m)) w, h = rect.width(), rect.height() printer = QtPrintSupport.QPrinter() printer.setWinPageSize(QtGui.QPageSize.A4) printer.setFullPage(True) is_landscape = False if w > h: is_landscape = True printer.setOrientation(QtPrintSupport.QPrinter.Landscape) else: printer.setOrientation(QtPrintSupport.QPrinter.Portrait) printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setOutputFileName(path) size = printer.pageLayout().pageSize().sizePoints() if is_landscape: pw, ph = size.height(), size.width() else: pw, ph = size.width(), size.height() scale = min(pw / w, ph / h) printer.setResolution(int(round(dpi / scale))) ph = int(round(h * (pw / w))) if is_landscape: printer.setPageSize( QtGui.QPageSize(QtCore.QSize(ph, pw), units=QtGui.QPageSize.Point)) else: printer.setPageSize( QtGui.QPageSize(QtCore.QSize(pw, ph), units=QtGui.QPageSize.Point)) painter = QtGui.QPainter(printer) self.scene().render(painter, source=rect) painter.end()
def __init__(self): super(mainWindow, self).__init__() self.setWindowTitle("Page Designer 1.0.0") self.setWindowIcon(QtGui.QIcon(":/icons/icon.png")) self.setObjectName("mainWindow") self.printer = QtPrintSupport.QPrinter( QtPrintSupport.QPrinter.HighResolution) self.printer.setPageSize(QtPrintSupport.QPrinter.A4) self.centralWidget = centralWidget(self.printer, self) self.setCentralWidget(self.centralWidget) # Init widgets self.snapbtn = snapButton(self.centralWidget.scene, self.centralWidget.propPanel.gridPropBox, self) self.toolBox = toolBox(self.centralWidget.scene, self.centralWidget.view, self.centralWidget.position, self.centralWidget, self.snapbtn) self.toolBox.addWidget(self.snapbtn) self.menuBar = menuBar(self.centralWidget.scene, self.centralWidget, self.toolBox.snap) self.statusBar = statusBar() self.setMenuBar(self.menuBar) self.addToolBar(self.toolBox) self.setStatusBar(self.statusBar) # Init actions not listed in toolBox act_selectAll = actionSelectAll(self.centralWidget.scene, self.centralWidget) self.addAction(act_selectAll) # add page borders to the viewport self.centralWidget.addBorders()
def exportAsPdf(window): mdView = window.ui.mdViewer if ("encrypted" in currentNote._details ) and currentNote._details["encrypted"] == "True": msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information, "Groot", "Cannot Export Encrypted Files", QtWidgets.QMessageBox.Ok) msg.setParent(window, QtCore.Qt.Window) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/icons/Icons/32x32/attention.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) msg.setWindowIcon(icon) msg.exec_() return filename, _ = QtWidgets.QFileDialog().getSaveFileName( None, "Export Pdf", "./") if filename != "": if QtCore.QFileInfo(filename).suffix() != "pdf": filename += ".pdf" printer = QtPrintSupport.QPrinter( QtPrintSupport.QPrinter.HighResolution) printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setOutputFileName(filename) mdView.document().print_(printer)
def generate_pdf(self, path: str, title: str = "Document", use_colors: bool = False, small: bool = False) -> bool: """Generate a multiple-page document, with passed title and list of strings""" # this function heavily relies on PySide for pdf creation, the import is local # to the function so that the class can still be used also without Pyside try: from PySide2 import QtGui from PySide2 import QtCore from PySide2 import QtPrintSupport except (ImportError, ValueError, IOError): logger.warning( "PySide2 is not properly installed, thus you cannot create a pdf file" ) self.display() return False # some preliminary tests if len(path) == 0: logger.warning("The passed file path is empty") return False path = os.path.abspath(path) if '.pdf' not in path.lower(): logger.warning( "The passed file name has not the pdf extension: %s" % path) return False path = Helper.truncate_too_long(path) if len(self.records) == 0: logger.warning("The passed string list is empty") return False # # INITIAL SETTINGS # logger.debug("output: %s" % path) # delete the passed filename if it already exists if os.path.exists(path): os.remove(path) # prepare some drawing tools blue_pen = QtGui.QPen(QtGui.QColor(30, 30, 255)) red_pen = QtGui.QPen(QtGui.QColor(255, 30, 30)) green_pen = QtGui.QPen(QtGui.QColor(30, 200, 30)) gray_pen = QtGui.QPen(QtGui.QColor(120, 120, 120)) black_pen = QtGui.QPen(QtGui.QColor(30, 30, 30)) if small: big_font = QtGui.QFont("Arial", 9) normal_font = QtGui.QFont("Arial", 6) bold_font = QtGui.QFont("Arial", 6, QtGui.QFont.Bold) small_font = QtGui.QFont("Arial", 5) else: big_font = QtGui.QFont("Arial", 10) normal_font = QtGui.QFont("Arial", 8) bold_font = QtGui.QFont("Arial", 8, QtGui.QFont.Bold) small_font = QtGui.QFont("Arial", 7) lc_flags = QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter | QtCore.Qt.TextWordWrap cc_flags = QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap # create the printer for pdf printer = QtPrintSupport.QPrinter( QtPrintSupport.QPrinter.HighResolution) printer.setCreator("HydrOffice") printer.setDocName("HydrOffice.pdf") printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setPageSize(QtPrintSupport.QPrinter.A4) printer.setOrientation(QtPrintSupport.QPrinter.Portrait) printer.setOutputFileName(path) page_rect = printer.pageRect() doc_width = page_rect.width() doc_height = page_rect.height() doc_margin = page_rect.x() # print(printer.getPageMargins(QtGui.QPrinter.DevicePixel)) # logger.info("Canvas: %sx%s" % (doc_width, doc_height)) # logger.info("Margin: %s" % doc_margin) # check if everything is ok if not printer.isValid(): logger.warning("the PDF printer is not valid") return False # # ACTUAL PRINTING # page_nr = 1 # a counter for pages section_nr = 1 row_counter = 1 if small: row_height = 330 else: row_height = 220 # this represents the height of a single row of text max_rows = (doc_height - 2 * doc_margin) / row_height hor_pad = row_height / 2 # logger.info("rows for page: %i" % max_rows) # here we start painting to the printer painter = QtGui.QPainter() if not painter.begin(printer): logger.warning("not painter begin on printer") return False def print_page_template(): """Internal helper function that print borders, logo, time stamp, etc.""" # external border painter.setPen(gray_pen) border_area = QtCore.QRect(doc_margin, doc_margin, doc_width - 2 * doc_margin, doc_height - 2 * doc_margin) painter.drawRect(border_area) # make top-area top_area = QtCore.QRect(doc_margin, doc_margin, doc_width - 2 * doc_margin, row_height * 2) painter.drawRect(top_area) # logo hyo_logo_path = os.path.join(AppInfo().app_media_path, 'poweredby.png') if not os.path.exists(hyo_logo_path): raise RuntimeError("Unable to find logo: %s" % hyo_logo_path) hyo_logo = QtGui.QPixmap(hyo_logo_path) # print("logo size: %sx%s" % (hyo_logo.width(), hyo_logo.height())) logo_area = QtCore.QRect( doc_width / 2 - hyo_logo.width() / 2, doc_margin + (row_height * 2 - hyo_logo.height()) / 2, hyo_logo.width(), hyo_logo.height()) painter.drawPixmap(logo_area, hyo_logo) # make bottom-area bottom_area = QtCore.QRect(doc_margin, doc_height - doc_margin - row_height, doc_width - 2 * doc_margin, row_height) painter.drawRect(bottom_area) # time-stamp now_time = datetime.datetime.now() painter.setFont(small_font) painter.drawText( bottom_area, cc_flags, "time-stamp: %s, %s v.%s" % (now_time.strftime("%a, %d %b %Y %H:%M:%S"), self.lib_name, self.lib_version)) # page number page_area = QtCore.QRect(doc_width - doc_margin - 2 * row_height, doc_height - doc_margin - row_height, 2 * row_height, row_height) # painter.drawRect(page_area) painter.drawText(page_area, lc_flags, "Page %s" % page_nr) # set back to 'normal' font painter.setPen(black_pen) painter.setFont(normal_font) return True print_page_template() row_area = QtCore.QRect(doc_margin + hor_pad, doc_margin, doc_width - 2 * doc_margin - 2 * hor_pad, row_height) # painter.drawRect(row_area) first_page = True for content_item in self.records: # title document only for the first page if first_page: # document title if small: row_counter = 4 else: row_counter = 3 painter.setPen(blue_pen) painter.setFont(big_font) row_area.moveTo(row_area.x(), row_area.y() + row_counter * row_height) painter.drawText(row_area, cc_flags, title) # painter.drawRect(row_area) # row_counter += 1 # set back to 'normal' font painter.setPen(black_pen) painter.setFont(normal_font) first_page = False # manage a new page creation if row_counter >= (max_rows - 4): if not printer.newPage(): logger.warning( "Failed in flushing page to disk, disk full?") return False page_nr += 1 print_page_template() row_area = QtCore.QRect( doc_margin + hor_pad, doc_margin + row_height, doc_width - 2 * doc_margin - 2 * hor_pad, row_height) row_counter = 1 row_area.moveTo(row_area.x(), row_area.y() + row_height) # painter.drawRect(row_area) last_item = content_item.split(' ')[-1] if last_item.isdigit(): if int(last_item) > 0: # troubles -> red pen if use_colors: painter.setPen(red_pen) painter.drawText(row_area, lc_flags, "- " + content_item) if use_colors: painter.setPen(black_pen) else: # all good -> black pen painter.drawText(row_area, lc_flags, "- " + content_item) elif last_item == "[SKIP_REP]": # skip report for this item if use_colors: painter.setPen(gray_pen) painter.drawText(row_area, lc_flags, "- " + content_item.rsplit(' ', 1)[0]) if use_colors: painter.setPen(black_pen) elif last_item == "[CHECK]" or last_item == "[TOTAL]": # the string is a section separator # leave an empty row row_area.moveTo(row_area.x(), row_area.y() + row_height) row_counter += 1 # write a numbered sections painter.setFont(bold_font) painter.drawText(row_area, lc_flags, "%s. %s" % (section_nr, content_item.rsplit( ' ', 1)[0])) # cut the final token painter.setFont(normal_font) section_nr += 1 elif last_item == "[SKIP_CHK]": # the string is a section separator if use_colors: painter.setPen(gray_pen) # leave an empty row row_area.moveTo(row_area.x(), row_area.y() + row_height) row_counter += 1 # write a numbered sections painter.setFont(bold_font) painter.drawText(row_area, lc_flags, "%s. %s" % (section_nr, content_item.rsplit( ' ', 1)[0])) # cut the final token painter.setFont(normal_font) section_nr += 1 if use_colors: painter.setPen(black_pen) elif last_item == "OK": # no issues, green ok if use_colors: painter.setPen(green_pen) painter.drawText(row_area, lc_flags, content_item) if use_colors: painter.setPen(black_pen) else: painter.drawText(row_area, lc_flags, content_item) row_counter += 1 # print("page %s, row %s" % (page_nr, row_counter)) # # FINISHING THE PRINTING # painter.end() return True
def save_clusters_as_pdf(tgt_path, samples): clusters = defaultdict(list) # {label: [sample, ...], ...} for sample in samples: if sample.cluster is None: continue clusters[sample.cluster].append(sample) if not clusters: return collect = {} for cluster in natsorted(clusters.keys()): collect[cluster] = natsorted(clusters[cluster], key=lambda sample: sample.id) clusters = collect renderer = QtSvg.QSvgRenderer() w_src_max = 0 h_src_max = 0 cmax = 0 for cluster in clusters: for sample in clusters[cluster]: cmax += 1 src_path = as_path(sample.resource.value, check_if_exists=False) renderer.load(src_path) rnd_size = renderer.defaultSize() w_src_max = max(w_src_max, rnd_size.width()) h_src_max = max(h_src_max, rnd_size.height()) printer = QtPrintSupport.QPrinter() printer.setWinPageSize(QtGui.QPageSize.A4) printer.setResolution(300) printer.setOrientation(QtPrintSupport.QPrinter.Portrait) printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setOutputFileName(tgt_path) w_max = printer.width() h_max = printer.height() scale = min(1, w_max / w_src_max, h_max / h_src_max) painter = QtGui.QPainter(printer) td = QtGui.QTextDocument() font = td.defaultFont() font.setPointSize(36) td.setDefaultFont(font) def init_page(printer, td, painter, cluster, page, new_page): if new_page: printer.newPage() td.setHtml("Cluster: %s, Page: %s" % (cluster, page)) td.drawContents(painter) return td.size().height() cnt = 0 for cluster in clusters: x = 0 y = 0 h_max_row = 0 page = 1 y = init_page(printer, td, painter, cluster, page, cnt > 0) for sample in clusters[cluster]: print("\rgen. pdf %d/%d " % (cnt + 1, cmax), end="") cnt += 1 src_path = as_path(sample.resource.value, check_if_exists=False) renderer.load(src_path) rnd_size = renderer.defaultSize() w = rnd_size.width() * scale h = rnd_size.height() * scale h_max_row = max(h_max_row, h) if x + w > w_max: x = 0 y += h_max_row h_max_row = h if y + h_max_row > h_max: x = 0 page += 1 y = init_page(printer, td, painter, cluster, page, True) renderer.render(painter, QtCore.QRectF(x, y, w, h)) x += w painter.end()
def __init__(self, parent=None): # Constructor of the class. super(UApp, self).__init__(parent) # Initialization of the class. UTools.__init__(self) # Initialization of the tools # print self.us1 # class with functions. self.apps = QtQuickWidgets.QQuickWidget(self.twid1) self.apps.setSource(QtCore.QUrl("apps.qml")) self.properties = self.apps.rootObject() self.gscene = QtWidgets.QGraphicsScene() self.gview = UGraphView(self.twid2) # Adding of the graphics view self.painter = QtGui.QPainter() # to the tab widget, adding self.gvlay = QtWidgets.QGridLayout() # scene and painter that can self.gvlay.addWidget(self.gview, 0, 0, 1, 1) self.gvlay.setContentsMargins(0, 0, 0, 0) self.twid2.setLayout(self.gvlay) # used, arrange with grid. self.frame1 = UFrame(self.twid3) # Create the first frame with self.frame1.setLineWidth(3) # parent as third widget. self.frame1.setFrameStyle(6) # Styled panel frame style. self.table = UTabView(self.frame1) # Creation of the table with self.table.setVisible(False) # parent as frame 1 and gets model = UTModel() # data from the model. self.table.setModel(model) # Set model data to the table. self.text_edit = UTextEd(self.frame1) # Text Edit field with self.layfr1 = QtWidgets.QGridLayout() # parent - the first frame. self.layfr1.addWidget(self.table, 0, 0, 1, 1) self.layfr1.addWidget(self.text_edit, 0, 0, 1, 1) self.layfr1.setContentsMargins(0, 0, 0, 0) self.frame1.setLayout(self.layfr1) # Layout for this field. self.frame2 = UFrame(self.twid3) # Second Frame with parent. self.frame2.setLineWidth(3) # Sets line width of the frame self.frame2.setFrameStyle(0) # and 0 - style No frame. self.frame2.setMaximumWidth(int(self.width() / 3)) self.label1 = ULabel(self.frame2) # Label for the second frame. self.label1.setText("User Information") self.label1.setAlignment(QtCore.Qt.AlignCenter) self.combox1 = UComBox(self.frame2) # Add the combobox with items. self.combox1.addItems(["Texts", "Table"]) self.combox1.setView(UListV()) # Combo popup list view. self.line_ed1 = ULineEd(self.frame2) # Line edit with placeholder. self.line_ed1.setPlaceholderText("Full Name...") self.line_ed2 = ULineEd(self.frame2) # Second will for user email. self.line_ed2.setPlaceholderText("Email...") self.line_ed3 = ULineEd(self.frame2) # Third field for password, self.line_ed3.setPlaceholderText("Password...") self.line_ed3.setEchoMode(QtWidgets.QLineEdit.Password) self.push_but1 = UBut1(self.frame2) # Adding button with text self.push_but1.setText("Save") # for saving operations. self.push_but2 = UBut1(self.frame2) # Adding button with text self.push_but2.setText("Ok") # for other operations. self.progress1 = UProgress(self.frame2) self.progress1.setRange(0, 0) # Progress bar with range. self.layfr2_1 = QtWidgets.QGridLayout() self.layfr2_1.addWidget(self.push_but1, 0, 0, 1, 1) self.layfr2_1.addWidget(self.push_but2, 0, 1, 1, 1) self.layfr2_1.addWidget(self.progress1, 1, 0, 1, 2) self.layfr2_1.setSpacing(3) # Widgets spacing for layout. self.layfr2 = QtWidgets.QGridLayout() # Second frame`s layout. self.layfr2.addWidget(self.combox1, 0, 0, 1, 1) self.layfr2.addWidget(self.label1, 1, 0, 1, 1) self.layfr2.addWidget(self.line_ed1, 2, 0, 1, 1) self.layfr2.addWidget(self.line_ed2, 3, 0, 1, 1) self.layfr2.addWidget(self.line_ed3, 4, 0, 1, 1) self.layfr2.addLayout(self.layfr2_1, 5, 0, 1, 1) self.layfr2.setSpacing(3) # Spacing between widgets. self.layfr2.setContentsMargins(3, 3, 3, 3) self.frame2.setLayout(self.layfr2) # Set layout to second frame. self.lay1 = QtWidgets.QGridLayout() # Layout for the third tabwid. self.lay1.addWidget(self.frame1, 0, 0, 1, 1) self.lay1.addWidget(self.frame2, 0, 1, 1, 1) self.twid3.setLayout( self.lay1) # Adding fdf.values[0]rames to tab widget. self.mb1.triggered.connect(self.files) self.mb2.triggered.connect(self.edit) # Calling files, edit, data, self.mb2_1.triggered.connect(self.edit_align) self.mb3.triggered.connect(self.data) # optins, and help function. self.mb4.triggered.connect(self.options) self.mb5.triggered.connect(self.on_help) self.qmlbut1 = self.properties.childItems()[0].childItems()[0] self.qmlbut1.clicked.connect(self.video_camera) self.qmlbut2 = self.properties.childItems()[0].childItems()[1] self.qmlbut2.clicked.connect(self.qml_apps) self.qmlbut3 = self.properties.childItems()[0].childItems()[2] self.qmlbut3.clicked.connect(self.jupyter) self.qmlbut4 = self.properties.childItems()[0].childItems()[3] self.qmlbut4.clicked.connect(self.web_browse) self.combox1.activated.connect(self.txt_table) self.push_but1.clicked.connect(self.save_data) self.push_but2.clicked.connect(self.vis) self.print_device = QtPrintSupport.QPrinter() self.actx = "" # Empty string for actions. self.qapp1 = 0 # Value for the qml button 1. self.qapp2 = 0 # Value for the qml button 2. self.qapp3 = 0 # Value for the qml button 3. self.qapp4 = 0 # Value for the qml button 4.
def save_catalog(path, sample_data, clusters, scale = 1/3, dpi = 600, line_width = 0.5, progress = None): # sample_data = {sample_id: [obj_id, descriptors], ...} # descriptors = { # profile = {Profile_Geometry, Profile_Rim, Profile_Bottom, Profile_Radius, Profile_Radius_Point, Profile_Rim_Point, Profile_Bottom_Point, Arc_Geometry: []} # details = {target_id: {Detail_Geometry, Detail_Closed, Detail_Filled}, ...} # inflections = {target_id: {Inflection_Geometry, Inflection_Dashed}, ...} # breaks = {target_id: {Break_Geometry}, ...} # } # clusters = {label: [sample_id, ...], ...} def get_picture(sample_id, descriptors, scale, line_width): picture = QtGui.QPicture() painter = QtGui.QPainter(picture) render_drawing(descriptors, painter, line_width, scale = scale, caption = sample_id) painter.end() return picture def init_cluster(td, painter, cluster_label, y): td.setHtml("Cluster: %s" % (cluster_label)) h = td.size().height() + 24 painter.translate(0, y) td.drawContents(painter) painter.translate(0, -y) return h labels = natsorted(clusters.keys()) sample_ids = set([]) for label in labels: for sample_id in clusters[label]: sample_ids.add(sample_id) cmax = len(sample_ids) + len(clusters) cnt = 1 drawings = {} for sample_id in sample_ids: if progress is None: print("\rrendering %d/%d " % (cnt, cmax), end = "") else: progress.update_state(text = "Rendering...", value = cnt, maximum = cmax) if progress.cancel_pressed(): return cnt += 1 drawings[sample_id] = get_picture(sample_id, sample_data[sample_id][1], scale, line_width) printer = QtPrintSupport.QPrinter() printer.setWinPageSize(QtGui.QPageSize.A4) printer.setResolution(dpi) printer.setOrientation(QtPrintSupport.QPrinter.Portrait) printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat) printer.setOutputFileName(path) w_max = printer.width() h_max = printer.height() painter = QtGui.QPainter(printer) td = QtGui.QTextDocument() font = td.defaultFont() font.setPointSize(48) td.setDefaultFont(font) x = 0 y = 0 h_max_row = 0 for label in labels: if progress is None: print("\rrendering %d/%d " % (cnt, cmax), end = "") else: progress.update_state(text = "Rendering...", value = cnt, maximum = cmax) if progress.cancel_pressed(): painter.end() os.remove(path) return cnt += 1 x = 0 y += h_max_row if h_max - y > 200: y += init_cluster(td, painter, label, y) else: printer.newPage() y = init_cluster(td, painter, label, 0) h_max_row = 0 for sample_id in clusters[label]: rect = drawings[sample_id].boundingRect() mul = printer.resolution() / drawings[sample_id].logicalDpiX() w = (rect.width() * mul) * 1.2 h = (rect.height() * mul) * 1.2 h_max_row = max(h_max_row, h) if x + w > w_max: x = 0 y += h_max_row h_max_row = h if y + h_max_row > h_max: printer.newPage() x = 0 y = init_cluster(td, painter, label, 0) painter.drawPicture(x, y, drawings[sample_id]) x += w painter.end()