def Get_Format(self, color_str): ''' Returns a QTextCharFormat object set for the given color. The color string should be understood by QColor.setNamedColor(). Suitable for feeding to setFormat(). ''' format = QTextCharFormat() # Wrap the color up. color = QColor() color.setNamedColor(color_str) format.setForeground(color) # TODO: other format stuff if desired, though nothing wanted # for now (stuff like bold might be set by fonts already). return format
def __init__(self, parent): """Summary Args: parent (TYPE): Description """ QSyntaxHighlighter.__init__(self, parent) self.parent = parent self.format = QTextCharFormat() self.format.setForeground(getBrushObj(Qt.white)) self.format.setBackground(getBrushObj(styles.INVALID_DNA_COLOR)) if styles.UNDERLINE_INVALID_DNA: self.format.setFontUnderline(True) self.format.setUnderlineColor(getColorObj(styles.INVALID_DNA_COLOR))
def format(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
def handlePaintRequest(self, printer): document = QTextDocument() document.setPageSize(QSizeF(printer.pageRect().size())) cursor = QTextCursor(document) tableFormat = QTextTableFormat() TableText = QTextCharFormat() TableText.setLayoutDirection(Qt.RightToLeft) tableFormat.setBackground(QColor('#d3fbf5')) tableFormat.setCellPadding(3) tableFormat.setCellSpacing(4) tableFormat.setLayoutDirection(Qt.RightToLeft) tableFormat.setBorderStyle(QTextTableFormat.BorderStyle_Double) TitrFormat = QTextCharFormat() fontTitr = QFont() fontTitr.setBold(True) TitrFormat.setFont(fontTitr) SotonFormat = QTextCharFormat() TitrFormat.setLayoutDirection(Qt.RightToLeft) SotonFormat.setFont(fontTitr) # SotonFormat.setBackground(QColor('#EEF9C9')) cursor.insertText(self.TableTitr+"\n", TitrFormat) model = self.ui.tableView_result.model() print(model) table = cursor.insertTable(model.rowCount()+1, model.columnCount(), tableFormat) headers = ['پلاک', 'متقاضی','نوع انجام کار', 'تاریخ بازدید', 'ساعت بازدید', 'نقشه بردار','نماینده','تاریخ ثبت', 'توضیحات'] self.tableResult.insertRows(10,10) for header in reversed(headers): cursor.insertText(header,SotonFormat) cursor.movePosition(QTextCursor.NextCell) for row in range(table.rows()): for column in reversed(range(table.columns())): cursor.insertText(self.tableResult.data(self.tableResult.index(row,column)),TableText) cursor.movePosition(QTextCursor.NextCell) cursor.movePosition(QTextCursor.NextBlock) cursor.insertText('- سامانه زمانبندی بازدید ثبت ماسال -', TitrFormat) # printer.setFullPage(True) document.print_(printer)
def __init__(self, parent=None): super(Highlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(Qt.darkBlue) keywordFormat.setFontWeight(QFont.Bold) keywordPatterns = [ "\\bchar\\b", "\\bclass\\b", "\\bconst\\b", "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b", "\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b", "\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b", "\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b", "\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b", "\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b", "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b", "\\bvolatile\\b", "\\bwhile\\b" ] self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in keywordPatterns] classFormat = QTextCharFormat() classFormat.setFontWeight(QFont.Bold) classFormat.setForeground(Qt.darkMagenta) self.highlightingRules.append( (QRegExp("\\bQ[A-Za-z]+\\b"), classFormat)) singleLineCommentFormat = QTextCharFormat() singleLineCommentFormat.setForeground(Qt.gray) self.highlightingRules.append( (QRegExp("//[^\n]*"), singleLineCommentFormat)) self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(Qt.red) quotationFormat = QTextCharFormat() quotationFormat.setForeground(Qt.darkGreen) self.highlightingRules.append((QRegExp("\".*\""), quotationFormat)) if_else_statement = QTextCharFormat() if_else_statement.setForeground(Qt.darkGreen) self.highlightingRules.append( (QRegExp("^.*if|else"), if_else_statement)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(Qt.blue) self.highlightingRules.append( (QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat)) self.commentStartExpression = QRegExp("/\\*") self.commentEndExpression = QRegExp("\\*/")
def writeMessage(self, message, type): """This writes both status and output messages to the log. For output messages also the correct encoding is re-applied: LilyPond writes filenames out in the system's filesystemencoding, while the messages are always written in UTF-8 encoding... """ if type == job.STDERR: # find filenames in message: parts = iter(errors.message_re.split(message.encode('latin1'))) msg = next(parts).decode('utf-8', 'replace') self.cursor.insertText(msg, self.textFormat(type)) enc = sys.getfilesystemencoding() for url, path, line, col, msg in zip(*itertools.repeat(parts, 5)): url = url.decode(enc) path = path.decode(enc) msg = msg.decode('utf-8', 'replace') if self._rawView: fmt = QTextCharFormat(self.textFormat(type)) display_url = url else: fmt = QTextCharFormat(self.textFormat("link")) display_url = os.path.basename(path) fmt.setAnchor(True) fmt.setAnchorHref(str(len(self._errors))) fmt.setToolTip(_("Click to edit this file")) pos = self.cursor.position() self.cursor.insertText(display_url, fmt) self.cursor.insertText(msg, self.textFormat(type)) self._errors.append((pos, self.cursor.position(), url)) else: if type == job.STDOUT: message = message.encode('latin1').decode('utf-8') super(LogWidget, self).writeMessage(message, type)
def __init__(self, parent=None): super(Highlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(Qt.darkBlue) keywordFormat.setFontWeight(QFont.Bold) keywordPatterns = [ """</?\w+\s+[^>]*>""", "<[/]?(html|body|head|title|div|a|br|form|input|b|p|i|center|span|font|table|tr|td|h[1-6])[/]?>" ] self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in keywordPatterns] self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(Qt.red) quotationFormat = QTextCharFormat() quotationFormat.setForeground(Qt.darkGreen) self.highlightingRules.append((QRegExp("\".*\""), quotationFormat)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(Qt.blue) self.highlightingRules.append( (QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat)) moreKeyWords = QTextCharFormat() moreKeyWords.setForeground(Qt.darkMagenta) moreKeyWords.setFontWeight(QFont.Bold) self.highlightingRules.append((QRegExp( "(id|class|src|border|width|height|style|name|type|value)="), moreKeyWords)) self.commentStartExpression = QRegExp("<!--") self.commentEndExpression = QRegExp("-->")
def __init__(self, parent, display_widget: QWebEngineView, settings_manager, thread_manager: ThreadManager, filename: str): super().__init__(parent) # Set attributes self.display_widget = display_widget self.SettingsManager = settings_manager self.ThreadManager = thread_manager self.lineNumberArea = LineNumberArea(self) self.InputTimer = QTimer(self) self.DocumentParsingTimer = QTimer(self) self.highlighter = MarkdownHighlighter(self.document(), self.SettingsManager) self.char_format = QTextCharFormat(self.currentCharFormat()) self.text_changed_since_save = False self.text_changed_since_render = False self.setMouseTracking(True) self.is_current_editor = False self.is_parsing_document = False self.filename = "" self.rendered_html = "" self.set_filename(filename) self.document_structure: dict = copy.deepcopy( defaults.document_info_template) self.ColorSchema = self.SettingsManager.color_schema # Connect signals to slots self.document().blockCountChanged.connect( self.updateLineNumberAreaWidth) self.updateRequest.connect(self.updateLineNumberArea) self.cursorPositionChanged.connect(self.on_TextEditor_CursorMoved) self.textChanged.connect(self.on_TextEditor_textChanged) self.selectionChanged.connect(self.on_TextEditor_CursorMoved) self.InputTimer.timeout.connect(self.on_InputTimer_timeout) self.DocumentParsingTimer.timeout.connect( self.on_DocumentParsingTimer_timeout) self.updateLineNumberAreaWidth(0) self.InputTimer.setSingleShot(True) self.DocumentParsingTimer.setSingleShot(True) self.read_settings() # Trigger it to highlight current line, when the editor is first opened self.on_TextEditor_CursorMoved()
def highlightCurrentLine(self, line, status): try: selection = self.sourceCodePlainTextEdit.document( ).findBlockByLineNumber(line) cursor = self.sourceCodePlainTextEdit.textCursor() line = selection.text() + " " cursor.setPosition(selection.position()) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) formats = QTextCharFormat() if status: formats.setBackground(QColor('red')) cursor.removeSelectedText() cursor.insertText(line, formats) except: print(traceback.format_exc())
def format(color, style=''): set_color = QColor() set_color.setNamedColor(color) format = QTextCharFormat() format.setForeground(set_color) if "bold" in style: format.setFontWeight(QFont.Bold) if "italic" in style: format.setFontItalic(True) if "underline" in style: set_color.setNamedColor("red") format.setFontUnderline(True) format.setUnderlineColor(set_color) return format
def format(color, estilo=''): _color = QColor() if type(color) is not str: _color.setRgb(color[0], color[1], color[2]) else: _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in estilo: _format.setFontWeight(QFont.Bold) if 'italic' in estilo: _format.setFontItalic(True) return _format
def format(color, bgcolor="", style=""): """Return a QTextCharFormat with the given attributes.""" _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if bgcolor: _format.setBackground(QColor(bgcolor)) if "bold" in style: _format.setFontWeight(QFont.Bold) if "italic" in style: _format.setFontItalic(True) return _format
def __init__(self, document): super().__init__(document) instruction_format = QTextCharFormat() instruction_format.setForeground(QColor(36, 147, 110)) instruction_format.setFontWeight(QFont.Bold) self.instructions = list(R_TYPE.keys()) + list(I_TYPE.keys()) + list(J_TYPE.keys()) instruction_patterns = ["\\b{}\\b".format(w) for w in self.instructions] self.highlightingRules = [(QRegExp(pattern), instruction_format) for pattern in instruction_patterns] number_format = QTextCharFormat() number_format.setForeground(QColor(0xD0104C)) self.highlightingRules.append((QRegExp("\\b0[Xx][0-9A-Fa-f]+\\b|-*\\b[\d]+\\b"), number_format)) register_format = QTextCharFormat() register_format.setForeground(QColor(0x0089A7)) self.registers = list(REGISTERS.keys()) register_patterns = [w[1:] for w in self.registers] print(register_patterns) self.highlightingRules += ([(QRegExp("\\$" + pattern), register_format) for pattern in register_patterns]) single_line_comment_format = QTextCharFormat() single_line_comment_format.setForeground(QColor(0x577C8A)) self.highlightingRules.append((QRegExp("//[^\n]*"), single_line_comment_format))
def __init__(self, parent=None): super(MdHiLiter, self).__init__(parent) self.formats = [0] * (LAST_CONSTRUCT + 1) titleFormat = QTextCharFormat() titleFormat.setForeground(QWidget().palette().highlight().color()) titleFormat.setFontWeight(QFont.Bold) self.setFormatFor(TITLE, titleFormat) boldFormat = QTextCharFormat() boldFormat.setForeground(QColor("#abb471")) boldFormat.setFontWeight(QFont.Bold) self.setFormatFor(BOLD, boldFormat) italicFormat = QTextCharFormat() italicFormat.setForeground(QColor("#bf8369")) italicFormat.setFontItalic(True) self.setFormatFor(ITALIC, italicFormat) boldItalicFormat = QTextCharFormat() boldItalicFormat.setForeground(QColor("#bf8369")) boldItalicFormat.setFontItalic(True) boldItalicFormat.setFontWeight(QFont.Bold) self.setFormatFor(BOLD_ITALIC, boldItalicFormat)
def initializeFormats(): baseFormat = QTextCharFormat() baseFormat.setFontFamily("courier") baseFormat.setFontPointSize(12) for name, color in (("normal", Qt.white), ("keyword", Qt.darkBlue), ("builtin", Qt.darkRed), ("constant", Qt.darkGreen), ("decorator", Qt.darkBlue), ("comment", Qt.darkGreen), ("string", Qt.darkYellow), ("number", Qt.darkMagenta), ("error", Qt.darkRed), ("pyqt", Qt.darkCyan)): format = QTextCharFormat(baseFormat) format.setForeground(QColor(color)) if name in ("keyword", "decorator"): format.setFontWeight(QFont.Bold) if name == "comment": format.setFontItalic(True) PythonHighlighter.Formats[name] = format
def format(color, style='', darker=100, lighter=100): """Return a QTextCharFormat with the given attributes. """ _color = QColor(color) _color = _color.darker(darker) _color = _color.lighter(lighter) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
def setup_textchar_formats(self): """Initializes all the text formatting for the syntax""" keyword_format = QTextCharFormat() keyword_format.setForeground(QColor('#F92672')) keyword_patterns = [ '\\#\\bdefine\\b', '\\#\\binclude\\b', '\\breturn\\b', '\\bconst\\b', '\\bvolatile\\b', '\\bextern\\b', '\\bstatic\\b' ] self.add_patterns(keyword_patterns, keyword_format) # C Types type_format = QTextCharFormat() type_format.setForeground(QColor('#66D9EF')) type_format.setFontItalic(True) type_patterns = [ '\\bchar\\b', '\\bint\\b', '\\blong\\b', '\\bshort\\b', '\\bsigned\\b', '\\bunsigned\\b', '\\bvoid\\b', '\\bstruct\\b', '\\btypedef\\b', '\\bdouble\\b', '\\bfloat\\b' ] self.add_patterns(type_patterns, type_format) # Quotations and include quote_format = QTextCharFormat() quote_format.setForeground(QColor('#E3D859')) self.add_patterns(['\".*\"', '\\<.*\\>'], quote_format) # Functions function_format = QTextCharFormat() function_format.setForeground(QColor('#A6E22E')) self.add_patterns(['\\b[A-Za-z0-9_]+(?=\\()'], function_format) # Single line comments single_comment_format = QTextCharFormat() single_comment_format.setForeground(Qt.gray) single_comment_format.setFontItalic(True) self.add_patterns(['\/\/[^\n]*'], single_comment_format)
def __init__(self, dockwidget): """Creates the Music View for the dockwidget.""" super(MusicView, self).__init__(dockwidget) self._positions = weakref.WeakKeyDictionary() self._currentDocument = None self._links = None self._clicking_link = False self._highlightFormat = QTextCharFormat() self._highlightMusicFormat = Highlighter() self._highlightRange = None self._highlightTimer = QTimer(singleShot=True, interval=250, timeout=self.updateHighlighting) self._highlightRemoveTimer = QTimer(singleShot=True, timeout=self.clearHighlighting) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.view = popplerview.View(self) self.view.MAX_ZOOM = 8.0 layout.addWidget(self.view) app.settingsChanged.connect(self.readSettings) self.readSettings() self.view.setViewMode(qpopplerview.FitWidth) self.view.surface().setPageLayout(qpopplerview.RowLayout()) self.view.surface().linkClicked.connect(self.slotLinkClicked) self.view.surface().linkHovered.connect(self.slotLinkHovered) self.view.surface().linkLeft.connect(self.slotLinkLeft) self.view.surface().setShowUrlTips(False) self.view.surface().linkHelpRequested.connect( self.slotLinkHelpRequested) self.view.viewModeChanged.connect(self.updateZoomInfo) self.view.surface().pageLayout().scaleChanged.connect( self.updateZoomInfo) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.showContextMenu) # react if cursor of current text document moves dockwidget.mainwindow().currentViewChanged.connect( self.slotCurrentViewChanged) view = dockwidget.mainwindow().currentView() if view: self.slotCurrentViewChanged(view)
def eltToStyle(elt): fmt = QTextCharFormat() if elt.get('bold'): fmt.setFontWeight(QFont.Bold if toBool(elt.get('bold')) else QFont.Normal) if elt.get('italic'): fmt.setFontItalic(toBool(elt.get('italic'))) if elt.get('underline'): fmt.setFontUnderline(toBool(elt.get('underline'))) if elt.get('textColor'): fmt.setForeground(QColor(elt.get('textColor'))) if elt.get('backgroundColor'): fmt.setBackground(QColor(elt.get('backgroundColor'))) if elt.get('underlineColor'): fmt.setUnderlineColor(QColor(elt.get('underlineColor'))) return fmt
def _format(color: Union[List[int], str], style: str = '') -> QTextCharFormat: """Return a QTextCharFormat with the given attributes.""" _color = QColor() if isinstance(color, str): _color.setNamedColor(color) else: _color.setRgb(color[0], color[1], color[2]) f = QTextCharFormat() f.setForeground(_color) if 'bold' in style: f.setFontWeight(QFont.Bold) if 'italic' in style: f.setFontItalic(True) return f
def log(self, _data): msg = _data[2] + "\r" colStr = _data[3] cursor = self.textBrowserHistory.textCursor() form = QTextCharFormat() form.setForeground(QBrush(QColor(colStr))) if self.HDMagFactor > 1.0: form.setFontPointSize(glo.QDSpy_fontPntSizeHistoryHD) else: form.setFontPointSize(glo.QDSpy_fontPntSizeHistory) cursor.movePosition(QTextCursor.End) cursor.setCharFormat(form) cursor.insertText(msg) self.textBrowserHistory.setTextCursor(cursor) self.textBrowserHistory.ensureCursorVisible()
def _fillFormat(color, style=None): _color = QColor(color) _format = QTextCharFormat() _format.setForeground(_color) if not style: style = FontStyle.Normal if style == FontStyle.Bold: _format.setFontWeight(QFont.Bold) elif style == FontStyle.Italic: _format.setFontItalic(True) elif style == FontStyle.BoldItalic: _format.setFontWeight(QFont.Bold) _format.setFontItalic(True) return _format
def __init__(self, **options): super(PugdebugFormatter, self).__init__(**options) for token, style in self.style: format = QTextCharFormat() if style['color']: format.setForeground(QColor('#' + style['color'])) if style['bgcolor']: format.setBackground(QColor('#' + style['bgcolor'])) if style['italic']: format.setFontItalic(True) if style['bold']: format.setFontWeight(QFont.Bold) self.styles[token] = format
def __init__(self, parent=None): """Initialize Highlighter with basic highlight options.""" super(HighLighter, self).__init__(parent) self.setHighlightRulesKeywords() self.setHighlightRulesNumeric() self.setHighlightRulesComments() self.setHighlightRulesTODO() self.setHighlightRulesSTR() self.setHighlightRulesFunction() self.multi_line_comment_format = QTextCharFormat() self.multi_line_comment_format.setForeground(Qt.darkGreen) self.comment_start_expression = QRegExp('/\*') self.comment_end_expression = QRegExp('\*/') return
def __init__(self, parent=None, user_name=None, host_name=None, cwd=None): super().__init__(parent) self.highlightingRules = [] self.name = user_name self.name2 = host_name self.cwd = cwd # print(self.cwd) first_list = [] most_used = ["cd", "clear", "history", "ls", "man", "pwd", "what", "type", "strace", "ltrace", "gdb", "cat", "chmod", "cp", "chown", "find", "grep", "locate", "mkdir", "rmdir", "rm", "mv", "vim", "nano", "rename", "touch", "wget", "zip", "tar", "gzip", "apt", "bg", "fg", "df", "free", "ip", "jobs", "kill", "killall", "mount", "umount", "ps", "sudo", "echo", "top", "uname", "whereis", "uptime", "whereis", "whoami", "exit" ] # most used linux commands, so we will highlight them! self.regex = { "class": "\\bclass\\b", "function": "[A-Za-z0-9_]+(?=\\()", "magic": "\\__[^']*\\__", "decorator": "@[^\n]*", "singleLineComment": "#[^\n]*", "quotation": "\"[^\"]*\"", "quotation2": "'[^\']*\'", "multiLineComment": "[-+]?[0-9]+", "int": "[-+]?[0-9]+", } """compgen -c returns all commands that you can run""" for f in most_used: nameFormat = QTextCharFormat() nameFormat.setForeground(QColor("#00ff00")) nameFormat.setFontItalic(True) self.highlightingRules.append((QRegExp("\\b" + f + "\\b"), nameFormat)) hostnameFormat = QTextCharFormat() hostnameFormat.setForeground(QColor("#12c2e9")) self.highlightingRules.append((QRegExp(self.name), hostnameFormat)) self.highlightingRules.append((QRegExp(self.name2), hostnameFormat)) otherFormat = QTextCharFormat() otherFormat.setForeground(QColor("#f7797d")) self.highlightingRules.append((QRegExp("~\/[^\s]*"), otherFormat)) quotation1Format = QTextCharFormat() quotation1Format.setForeground(QColor("#96c93d")) self.highlightingRules.append((QRegExp("\"[^\"]*\""), quotation1Format)) quotation2Format = QTextCharFormat() quotation2Format.setForeground(QColor("#96c93d")) self.highlightingRules.append((QRegExp("'[^\']*\'"), quotation2Format)) integerFormat = QTextCharFormat() integerFormat.setForeground(QColor("#cc5333")) integerFormat.setFontItalic(True) self.highlightingRules.append((QRegExp("\\b[-+]?[0-9]+\\b"), integerFormat))
def setFormat(style): """Return a QTextCharFormat with the given attributes. """ _style = style.split() _color = QColor() _format = QTextCharFormat() _color.setNamedColor(_style[0]) _format.setForeground(_color) for s in _style[1:]: if 'bold' in s: _format.setFontWeight(QFont.Bold) if 'italic' in s: _format.setFontItalic(True) return _format
def SaveTableImage(table): pixmap = table.grab() pixmap.save("widget.png") SaveTableImage(table) nrows = table.rowCount() ncols = table.columnCount() doc = QTextDocument() cursor = QTextCursor(doc) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(0) tableFormat.setCellSpacing(0) tableFormat.setBorder(1) tableFormat.setBorderBrush(QBrush(Qt.SolidPattern)) tableFormat.clearColumnWidthConstraints() textTable = cursor.insertTable(nrows + 1, ncols, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setBackground(QColor("#DADADA")) for i in range(ncols): cell = textTable.cellAt(0, i) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText(table.horizontalHeaderItem(i).text()) for i in range(nrows): for j in range(ncols): item = table.item(i, j) t = "" if item is None else str(item.text()) # if item.text().iEmpty(): # table.setItem(i,j,QTableWidgetItem("0")) cell = textTable.cellAt(i + 1, j) cellCursor = cell.firstCursorPosition() cellCursor.insertText(t) cursor.movePosition(QTextCursor.End) printer = QPrinter(QPrinter.PrinterResolution) printer.setPaperSize(QPrinter.A4) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName("w8.pdf") doc.setDocumentMargin(0) doc.setTextWidth(5) doc.print(printer)
def html_copy(cursor, scheme='editor', number_lines=False): """Return a new QTextDocument with highlighting set as HTML textcharformats. The cursor is a cursor of a document.Document instance. If the cursor has a selection, only the selection is put in the new document. If number_lines is True, line numbers are added. """ data = textformats.formatData(scheme) doc = QTextDocument() doc.setDefaultFont(data.font) doc.setPlainText(cursor.document().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document()))) if cursor.hasSelection(): # cut out not selected text start, end = cursor.selectionStart(), cursor.selectionEnd() cur1 = QTextCursor(doc) cur1.setPosition(start, QTextCursor.KeepAnchor) cur2 = QTextCursor(doc) cur2.setPosition(end) cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) cur2.removeSelectedText() cur1.removeSelectedText() if number_lines: c = QTextCursor(doc) f = QTextCharFormat() f.setBackground(QColor('#eeeeee')) if cursor.hasSelection(): num = cursor.document().findBlock( cursor.selectionStart()).blockNumber() + 1 last = cursor.document().findBlock(cursor.selectionEnd()) else: num = 1 last = cursor.document().lastBlock() lastnum = last.blockNumber() + 1 padding = len(format(lastnum)) block = doc.firstBlock() while block.isValid(): c.setPosition(block.position()) c.setCharFormat(f) c.insertText('{0:>{1}d} '.format(num, padding)) block = block.next() num += 1 return doc
def __init__(self, text, tab_, base, existing, *args, **kwargs): super().__init__(*args, **kwargs) """ xyzcba""" #modal coomnds self.tab_ = tab_ self.base = base self.setWordWrapMode(QTextOption.NoWrap) self.existing = existing self.start_point = None #todo self.setStyleSheet("background-color: {}".format(color4)) if text: self.setPlainText(text) self.changed = False #self.LastGCod = 0 self.zoomIn(5) self.fmt = QTextCharFormat() self.fmt.setUnderlineColor(Qt.red) self.fmt.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline) self.setPlaceholderText('Enjoy your work, please!') #number line self.lineNumberArea = QLineNumberArea(self) self.blockCountChanged.connect(self.updateLineNumberAreaWidth) self.cursorPositionChanged.connect(self.highlightCurrentLine) self.updateLineNumberAreaWidth(0) self.setAcceptDrops(True) self.updateRequest.connect(self.updateLineNumberArea) self.installEventFilter(self) self._document = self.document() #undo/redo self.undoStack = MyStack(self) self.undoAction = self.undoStack.createUndoAction( self, self.tr("&Undo")) self.undoAction.setShortcuts(QKeySequence.Undo) self.redoAction = self.undoStack.createRedoAction( self, self.tr("&Redo")) self.redoAction.setShortcuts(QKeySequence.Redo) self._document.contentsChange.connect(self.onChange) #self.textChanged.connect(self.textChanged_check) #contex menu Settings self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.__contextMenu) self.arithmetic_ones()
def highlight(self, selection_start, selection_end, color): ''' Color selected text in the content section ''' cursor = self.content_text.textCursor() cursor.setPosition(int(selection_start)) cursor.setPosition(int(selection_end), QTextCursor.KeepAnchor) fmt = QTextCharFormat() if isinstance(color, str): fmt.setBackground(QColor("transparent")) elif isinstance(color, tuple) or isinstance(color, list): if len(color) == 3: fmt.setBackground(QColor(color[0], color[1], color[2])) elif len(color) == 4: fmt.setBackground( QColor(color[0], color[1], color[2], color[3])) cursor.setCharFormat(fmt)