def drawContents(self, painter): """ Reimplementation of drawContents to limit the drawing inside `textRext`. """ painter.setPen(self.__color) painter.setFont(self.font()) if self.__textRect: rect = self.__textRect else: rect = self.rect().adjusted(5, 5, -5, -5) if Qt.mightBeRichText(self.__message): doc = QTextDocument() doc.setHtml(self.__message) doc.setTextWidth(rect.width()) cursor = QTextCursor(doc) cursor.select(QTextCursor.Document) fmt = QTextBlockFormat() fmt.setAlignment(self.__alignment) cursor.mergeBlockFormat(fmt) painter.save() painter.translate(rect.topLeft()) doc.drawContents(painter) painter.restore() else: painter.drawText(rect, self.__alignment, self.__message)
def highlightBlockBefore(self, text): """Highlighting to do before anything else. When subclassing basicHighlighter, you must call highlightBlockBefore before you do any custom highlighting. """ bf = QTextBlockFormat(self._defaultBlockFormat) bf.setAlignment(QTextCursor(self.currentBlock()).blockFormat().alignment()) QTextCursor(self.currentBlock()).setBlockFormat(bf)
def highlightBlockBefore(self, text): """Highlighting to do before anything else. When subclassing basicHighlighter, you must call highlightBlockBefore before you do any custom highlighting. """ bf = QTextBlockFormat(self._defaultBlockFormat) bf.setAlignment(QTextCursor(self.currentBlock()).blockFormat().alignment()) QTextCursor(self.currentBlock()).setBlockFormat(bf)
def getThemeBlockFormat(themeDatas): bf = QTextBlockFormat() bf.setAlignment(Qt.AlignLeft if themeDatas["Spacings/Alignment"] == 0 else Qt.AlignCenter if themeDatas["Spacings/Alignment"] == 1 else Qt.AlignRight if themeDatas["Spacings/Alignment"] == 2 else Qt.AlignJustify) bf.setLineHeight(themeDatas["Spacings/LineSpacing"], QTextBlockFormat.ProportionalHeight) bf.setTextIndent(themeDatas["Spacings/TabWidth"] * 1 if themeDatas["Spacings/IndentFirstLine"] else 0) bf.setTopMargin(themeDatas["Spacings/ParagraphAbove"]) bf.setBottomMargin(themeDatas["Spacings/ParagraphBelow"]) return bf
def getThemeBlockFormat(themeDatas): bf = QTextBlockFormat() bf.setAlignment(Qt.AlignLeft if themeDatas["Spacings/Alignment"] == 0 else Qt.AlignCenter if themeDatas["Spacings/Alignment"] == 1 else Qt.AlignRight if themeDatas["Spacings/Alignment"] == 2 else Qt.AlignJustify) bf.setLineHeight(themeDatas["Spacings/LineSpacing"], QTextBlockFormat.ProportionalHeight) bf.setTextIndent(themeDatas["Spacings/TabWidth"] * 1 if themeDatas["Spacings/IndentFirstLine"] else 0) bf.setTopMargin(themeDatas["Spacings/ParagraphAbove"]) bf.setBottomMargin(themeDatas["Spacings/ParagraphBelow"]) return bf
def set_text_alignment(self): ''' Apply the required text alignment within the text box ''' alignment = self.parentItem().text_alignment self.setTextWidth(self.boundingRect().width()) fmt = QTextBlockFormat() fmt.setAlignment(alignment) cursor = self.textCursor() cursor.select(QTextCursor.Document) cursor.mergeBlockFormat(fmt) cursor.clearSelection() self.setTextCursor(cursor)
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 insertImage(self, qimage, image_name): self.moveCursor(QTextCursor.End) resource_path = os.path.join(self.resource_folder, image_name) + '.png' self.document().addResource(QTextDocument.ImageResource, QUrl(resource_path), QVariant(qimage)) image_format = QTextImageFormat() image_format.setName(resource_path) cursor = self.textCursor() block_format = QTextBlockFormat() block_format.setAlignment(Qt.AlignCenter) cursor.insertBlock(block_format) cursor.insertImage(image_format) cursor.insertBlock(block_format) self.image_resources[resource_path] = qimage
def show(self): """ No need since we print it as soon as we add a row """ if self.tab_initialized: self.text_edit.moveCursor(QTextCursor.End) self.text_edit.setTextColor(mapColor('k')) cursor = self.text_edit.textCursor() block_format = QTextBlockFormat() block_format.setAlignment(mapAlignment(Align.Center)) cursor.insertBlock(block_format) cursor.insertHtml(self.html_table_widget.show()) cursor.insertBlock(block_format) self.text_edit.resetFontSize() else: self.table_widget.show()
def formatBlock(self, block, state): """Apply transformation to given block.""" blockFormat = QTextBlockFormat() if state == State.BLOCKQUOTE_LINE: # Number of tabs n = block.text().indexOf(QRegExp(r'[^\t]'), 0) blockFormat.setIndent(0) blockFormat.setTextIndent(-self.tabStopWidth * n) blockFormat.setLeftMargin(self.tabStopWidth * n) # blockFormat.setRightMargin(self.editor.contentsRect().width() # - self.editor.lineNumberAreaWidth() # - fm.width("X") * self.editor.LimitLine # + self.editor.tabStopWidth()) blockFormat.setAlignment(Qt.AlignJustify) if self.name == "Default": blockFormat.setTopMargin(5) blockFormat.setBottomMargin(5) elif state == State.HEADER_LINE: blockFormat.setBackground(QColor("#EEEEEE")) elif state in State.LIST: data = blockUserData.getUserData(block) if str(data.listSymbol()) in "+-": blockFormat.setBackground(QColor("#EEFFEE")) else: blockFormat.setBackground(QColor("#EEEEFA")) n = blockUserData.getUserData(block).leadingSpaces() + 1 f = QFontMetrics(QFont(self.defaultFontFamily, self._defaultCharFormat.font().pointSize())) fm = f.width(" " * n + blockUserData.getUserData(block).listSymbol()) blockFormat.setTextIndent(-fm) blockFormat.setLeftMargin(fm) if blockUserData.getUserState(block) == State.LIST_BEGINS and \ self.name == "Default": blockFormat.setTopMargin(5) return blockFormat
def CreatePDF(self, out, timestamp, data, frame, rows, columns, fileName, VManager): ''' Create PDF QgsTask ''' QCoreApplication.processEvents() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) font_normal = QFont("Helvetica", 10, QFont.Normal) font_bold = QFont("Helvetica", 12, QFont.Bold) printer = QPrinter(QPrinter.HighResolution) printer.setOrientation(QPrinter.Portrait) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) printer.setPaperSize(QPrinter.A4) printer.setOutputFileName(out) printer.setPageMargins(15, 15, 15, 15, QPrinter.Point) printer.setColorMode(QPrinter.Color) document = QTextDocument() document.setDefaultFont(font_normal) cursor = QTextCursor(document) cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.insertHtml(""" <p style='text-align: center;'> <img style='display: block; margin-left: auto; margin-right: auto;' src=\':/imgFMV/images/header_logo.png\' width='200' height='25' /> </p> <p style='text-align: center;'> <strong>Video : </strong>%s<strong> </p> <p style='text-align: center;'> <strong>TimeStamp : </strong>%s</p><br><br> """ % (fileName, timestamp)) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(2) centerFormat = QTextBlockFormat() centerFormat.setAlignment(Qt.AlignCenter) cursor.insertBlock(centerFormat) textTable = cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setFont(font_bold) tableHeaderFormat.setBackground(QColor("#67b03a")) tableHeaderFormat.setForeground(Qt.white) alternate_background = QTextCharFormat() alternate_background.setBackground(QColor("#DDE9ED")) for column in range(columns): cell = textTable.cellAt(0, column) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText(VManager.horizontalHeaderItem(column).text()) row = 0 for key in sorted(data.keys()): cell0 = textTable.cellAt(row + 1, 0) cell1 = textTable.cellAt(row + 1, 1) cell2 = textTable.cellAt(row + 1, 2) if (row + 1) % 2 == 0: cell0.setFormat(alternate_background) cell1.setFormat(alternate_background) cell2.setFormat(alternate_background) cellCursor0 = cell0.firstCursorPosition() cellCursor0.insertText(str(key)) cellCursor1 = cell1.firstCursorPosition() cellCursor1.insertText(str(data[key][0])) cellCursor2 = cell2.firstCursorPosition() cellCursor2.insertText(str(data[key][1])) row += 1 cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertHtml(""" <br><p style='text-align: center;'><strong>Current Frame</strong></p><br> """) centerFormat = QTextBlockFormat() centerFormat.setAlignment(Qt.AlignHCenter) cursor.insertBlock(centerFormat) cursor.insertImage(frame.scaledToWidth(500)) QCoreApplication.processEvents() document.print_(printer) QCoreApplication.processEvents()
def loadFontSettings(self): if self._fromTheme or \ not self._index or \ type(self._index.model()) != outlineModel or \ self._column != Outline.text.value: return opt = settings.textEditor f = QFont() f.fromString(opt["font"]) background = opt["background"] if not opt["backgroundTransparent"] else "transparent" foreground = opt["fontColor"] if not opt["backgroundTransparent"] else S.text # self.setFont(f) self.setStyleSheet("""QTextEdit{{ background: {bg}; color: {foreground}; font-family: {ff}; font-size: {fs}; margin: {mTB}px {mLR}px; {maxWidth} }} """.format( bg=background, foreground=foreground, ff=f.family(), fs="{}pt".format(str(f.pointSize())), mTB = opt["marginsTB"], mLR = opt["marginsLR"], maxWidth = "max-width: {}px;".format(opt["maxWidth"]) if opt["maxWidth"] else "", ) ) # We set the parent background to the editor's background in case # there are margins. We check that the parent class is a QWidget because # if textEditView is used in fullScreenEditor, then we don't want to # set the background. if self.parent().__class__ == QWidget: self.parent().setStyleSheet(""" QWidget#{name}{{ background: {bg}; }}""".format( # We style by name, otherwise all heriting widgets get the same # colored background, for example context menu. name=self.parent().objectName(), bg=background, )) cf = QTextCharFormat() # cf.setFont(f) # cf.setForeground(QColor(opt["fontColor"])) self.setCursorWidth(opt["cursorWidth"]) bf = QTextBlockFormat() bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight) bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0) bf.setTopMargin(opt["spacingAbove"]) bf.setBottomMargin(opt["spacingBelow"]) bf.setAlignment(Qt.AlignLeft if opt["textAlignment"] == 0 else Qt.AlignCenter if opt["textAlignment"] == 1 else Qt.AlignRight if opt["textAlignment"] == 2 else Qt.AlignJustify) self._defaultCharFormat = cf self._defaultBlockFormat = bf if self.highlighter: self.highlighter.setMisspelledColor(QColor(opt["misspelled"])) self.highlighter.setDefaultCharFormat(self._defaultCharFormat) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
def printViaQCursor(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return logo = QPixmap(":/logo.png") headFormat = QTextBlockFormat() headFormat.setAlignment(Qt.AlignLeft) headFormat.setTextIndent(self.printer.pageRect().width() - logo.width() - 216) bodyFormat = QTextBlockFormat() bodyFormat.setAlignment(Qt.AlignJustify) lastParaBodyFormat = QTextBlockFormat(bodyFormat) lastParaBodyFormat.setPageBreakPolicy( QTextFormat.PageBreak_AlwaysAfter) rightBodyFormat = QTextBlockFormat() rightBodyFormat.setAlignment(Qt.AlignRight) headCharFormat = QTextCharFormat() headCharFormat.setFont(QFont("Helvetica", 10)) bodyCharFormat = QTextCharFormat() bodyCharFormat.setFont(QFont("Times", 11)) redBodyCharFormat = QTextCharFormat(bodyCharFormat) redBodyCharFormat.setForeground(Qt.red) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(2) document = QTextDocument() cursor = QTextCursor(document) mainFrame = cursor.currentFrame() page = 1 for statement in self.statements: cursor.insertBlock(headFormat, headCharFormat) cursor.insertImage(":/logo.png") for text in ("Greasy Hands Ltd.", "New Lombard Street", "London", "WC13 4PX", QDate.currentDate().toString(DATE_FORMAT)): cursor.insertBlock(headFormat, headCharFormat) cursor.insertText(text) for line in statement.address.split(", "): cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText(line) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Dear {0},".format(statement.contact)) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) balance = statement.balance() cursor.insertText( "The balance of your account is $ {0:,.2f}.".format( float(balance))) if balance < 0: cursor.insertBlock(bodyFormat, redBodyCharFormat) cursor.insertText("Please remit the amount owing " "immediately.") else: cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We are delighted to have done " "business with you.") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Transactions:") table = cursor.insertTable(len(statement.transactions), 3, tableFormat) row = 0 for date, amount in statement.transactions: cellCursor = table.cellAt(row, 0).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) cellCursor.insertText(date.toString(DATE_FORMAT), bodyCharFormat) cellCursor = table.cellAt(row, 1).firstCursorPosition() if amount > 0: cellCursor.insertText("Credit", bodyCharFormat) else: cellCursor.insertText("Debit", bodyCharFormat) cellCursor = table.cellAt(row, 2).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) format = bodyCharFormat if amount < 0: format = redBodyCharFormat cellCursor.insertText("$ {0:,.2f}".format(float(amount)), format) row += 1 cursor.setPosition(mainFrame.lastPosition()) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We hope to continue doing business " "with you,") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Yours sincerely") cursor.insertBlock(bodyFormat) if page == len(self.statements): cursor.insertBlock(bodyFormat, bodyCharFormat) else: cursor.insertBlock(lastParaBodyFormat, bodyCharFormat) cursor.insertText("K. Longrey, Manager") page += 1 document.print_(self.printer)
def loadFontSettings(self): if self._fromTheme or \ not self._index or \ type(self._index.model()) != outlineModel or \ self._column != Outline.text: return opt = settings.textEditor f = QFont() f.fromString(opt["font"]) background = (opt["background"] if not opt["backgroundTransparent"] else "transparent") foreground = opt["fontColor"] # if not opt["backgroundTransparent"] # else S.text # self.setFont(f) self.setStyleSheet("""QTextEdit{{ background: {bg}; color: {foreground}; font-family: {ff}; font-size: {fs}; margin: {mTB}px {mLR}px; {maxWidth} }} """.format( bg=background, foreground=foreground, ff=f.family(), fs="{}pt".format(str(f.pointSize())), mTB = opt["marginsTB"], mLR = opt["marginsLR"], maxWidth = "max-width: {}px;".format(opt["maxWidth"]) if opt["maxWidth"] else "", ) ) self._defaultFontSize = f.pointSize() # We set the parent background to the editor's background in case # there are margins. We check that the parent class is a QWidget because # if textEditView is used in fullScreenEditor, then we don't want to # set the background. if self.parent().__class__ == QWidget: self.parent().setStyleSheet(""" QWidget#{name}{{ background: {bg}; }}""".format( # We style by name, otherwise all inheriting widgets get the same # colored background, for example context menu. name=self.parent().objectName(), bg=background, )) cf = QTextCharFormat() # cf.setFont(f) # cf.setForeground(QColor(opt["fontColor"])) self.setCursorWidth(opt["cursorWidth"]) bf = QTextBlockFormat() bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight) bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0) bf.setTopMargin(opt["spacingAbove"]) bf.setBottomMargin(opt["spacingBelow"]) bf.setAlignment(Qt.AlignLeft if opt["textAlignment"] == 0 else Qt.AlignCenter if opt["textAlignment"] == 1 else Qt.AlignRight if opt["textAlignment"] == 2 else Qt.AlignJustify) self._defaultCharFormat = cf self._defaultBlockFormat = bf if self.highlighter: self.highlighter.updateColorScheme() self.highlighter.setMisspelledColor(QColor(opt["misspelled"])) self.highlighter.setDefaultCharFormat(self._defaultCharFormat) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)