def __init__(self, parent, blackbold_patterns, redbold_patterns): ''' Define highlighting rules - inputs = lists of patterns ''' super(Highlighter, self).__init__(parent) self.highlighting_rules = [] # Black bold items (allowed keywords) black_bold_format = QTextCharFormat() black_bold_format.setFontWeight(QFont.Bold) self.highlighting_rules = [(QRegExp(pattern, cs=Qt.CaseInsensitive), black_bold_format) for pattern in blackbold_patterns] # Red bold items (reserved keywords) red_bold_format = QTextCharFormat() red_bold_format.setFontWeight(QFont.Bold) red_bold_format.setForeground(Qt.red) for pattern in redbold_patterns: self.highlighting_rules.append( (QRegExp(pattern, cs=Qt.CaseInsensitive), red_bold_format)) # Comments comment_format = QTextCharFormat() comment_format.setForeground(Qt.darkBlue) comment_format.setFontItalic(True) self.highlighting_rules.append((QRegExp('--[^\n]*'), comment_format))
def __init__(self): self.start = 0 self.stop = 0 f = self.highlightFormat = QTextCharFormat() f.setForeground(Qt.blue) #f.setFontWeight(QFont.Bold) // this will cause text width change f.setFontUnderline(True) f.setUnderlineColor(Qt.red) f.setUnderlineStyle(QTextCharFormat.DashUnderline) f = self.openFormat = self.closeFormat = QTextCharFormat() f.setForeground(Qt.red)
def __init__(self, parent=None): """ @param parent QObject or QTextDocument or QTextEdit or None """ super(CppHighlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(HLS_KEYWORD_COLOR) keywordFormat.setFontWeight(QFont.Bold) self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in self.KEYWORD_PATTERNS] typeFormat = QTextCharFormat() typeFormat.setForeground(HLS_TYPE_COLOR) typeFormat.setFontWeight(QFont.Bold) self.highlightingRules.extend([(QRegExp(pattern), typeFormat) for pattern in self.TYPE_PATTERNS]) constantFormat = QTextCharFormat() constantFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.extend([(QRegExp(pattern), constantFormat) for pattern in self.CONSTANT_PATTERNS]) classFormat = QTextCharFormat() classFormat.setFontWeight(QFont.Bold) classFormat.setForeground(HLS_CLASS_COLOR) self.highlightingRules.append((QRegExp(r"\bQ[A-Za-z]+\b"), classFormat)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(HLS_FUNCTION_COLOR) self.highlightingRules.append((QRegExp(r"\b[A-Za-z0-9_]+(?=\()"), functionFormat)) quotationFormat = QTextCharFormat() quotationFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.append((QRegExp(r'"[^"]*"'), quotationFormat)) # This must comes before the line comments since they conficts pragmaFormat = QTextCharFormat() pragmaFormat.setForeground(HLS_PRAGMA_COLOR) self.highlightingRules.append((QRegExp(r"#[^\n]*"), pragmaFormat)) self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(HLS_COMMENT_COLOR) singleLineCommentFormat = QTextCharFormat() singleLineCommentFormat.setForeground(HLS_COMMENT_COLOR) self.highlightingRules.append((QRegExp("//[^\n]*"), singleLineCommentFormat)) self.commentStartExpression = QRegExp(r"/\*") self.commentEndExpression = QRegExp(r"\*/")
def foo(self): fmt = QTextCharFormat() fmt.setObjectType(QAbstractTextDocumentLayoutTest.objectType) cursor = self.textEdit.textCursor() cursor.insertText(py3k.unichr(0xfffc), fmt) self.textEdit.setTextCursor(cursor) self.textEdit.close()
def __init__(self): self.blockFormat = QTextBlockFormat() self.blockFormat.setAlignment(Qt.AlignLeft) self.charFormat = QTextCharFormat() self.frameFormat = QTextFrameFormat() self.frameFormat.setTopMargin(0) self.frameFormat.setBottomMargin(0) self.frameFormat.setLeftMargin(0) self.frameFormat.setPosition(QTextFrameFormat.InFlow)
def __init__(self, state, parent=None): super().__init__(parent) self.state = state self.unknownWords = [] self.wordsToIgnore = set() self.spellFormat = QTextCharFormat() self.spellFormat.setFontUnderline(True) self.spellFormat.setUnderlineColor(Qt.red) self.spellFormat.setUnderlineStyle(QTextCharFormat.WaveUnderline)
def createFormat(self): """ Create a QTextCharformat and saves it in self.class_format""" self.class_format = QTextCharFormat() self.class_format.setFontFamily(self.font_family) if self.use_font_size: self.class_format.setFontPointSize(self.font_size) self.class_format.setForeground(self.font_color) self.class_format.setFontWeight(self.font_weight) self.class_format.setFontItalic(self.font_style) self.class_format.setFontUnderline(self.font_underline)
def __init__(self, parent=None): """ @param parent QObject or QTextDocument or QTextEdit or None """ super(YouTubeHighlighter, self).__init__(parent) self._format = QTextCharFormat() self._format.setForeground(Qt.blue) #self._format.setFontWeight(QFont.Bold) self._format.setFontUnderline(True) self._format.setUnderlineColor(Qt.red) self._format.setUnderlineStyle(QTextCharFormat.DashUnderline)
def formatConverterFunction(format): if format == qutepart.syntax.TextFormat(): return None # Do not apply default format. Performance optimization qtFormat = QTextCharFormat() qtFormat.setForeground(QBrush(QColor(format.color))) qtFormat.setBackground(QBrush(QColor(format.background))) qtFormat.setFontItalic(format.italic) qtFormat.setFontWeight(QFont.Bold if format.bold else QFont.Normal) qtFormat.setFontUnderline(format.underline) qtFormat.setFontStrikeOut(format.strikeOut) return qtFormat
def txformat(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 highlightBlock(self, text): if not self.dict: return text = unicode(text) error_format = QTextCharFormat() error_format.setUnderlineColor(Qt.red) error_format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline) for word_object in re.finditer(self.WORDS, text): if not self.dict.check(word_object.group()): self.setFormat(word_object.start(), word_object.end() - word_object.start(), error_format)
def highlightBlock(self, text): """@reimp @public""" dic = self.__d.dic if not dic: return WORDS = "(?iu)[\w']+" #WORDS = "(?iu)[\w]+" # ' is not considered as part of a world fmt = QTextCharFormat() fmt.setUnderlineColor(Qt.red) fmt.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline) for word_object in re.finditer(WORDS, text): if not dic.check(word_object.group()): self.setFormat(word_object.start(), word_object.end() - word_object.start(), fmt)
def tesIterator(self): edit = QTextEdit() cursor = edit.textCursor() fmt = QTextCharFormat() frags = [] for i in range(10): fmt.setFontPointSize(i + 10) frags.append("block%d" % i) cursor.insertText(frags[i], fmt) doc = edit.document() block = doc.begin() index = 0 for i in block: self.assertEqual(i.fragment().text(), frags[index]) index += 1
def mouseMoveEvent(self, event): if event.modifiers() & Qt.ControlModifier: self.clear_underline() cursor, line = self._get_line_cursor(event.pos()) for goto in self.gotos: if line.strip().startswith(goto): fmt = QTextCharFormat() fmt.setFontUnderline(True) fmt.setUnderlineStyle(QTextCharFormat.WaveUnderline) fmt.setUnderlineColor(QtGui.QColor('blue')) # cursor.clearSelection() cursor.select(QTextCursor.BlockUnderCursor) cursor.beginEditBlock() cursor.setCharFormat(fmt) cursor.endEditBlock() break super(myCodeWidget, self).mouseMoveEvent(event)
def _add_table(self, tab, cursor): fmt = QTextCharFormat() fmt.setFont(QFont(self.factory.font_name)) fmt.setFontPointSize(self.factory.font_size) bc = QColor(self.factory.bg_color) if self.factory.bg_color else None ec, oc, hc = bc, bc, bc if self.factory.even_color: ec = QColor(self.factory.even_color) if self.factory.odd_color: oc = QColor(self.factory.odd_color) if self.factory.header_color: hc = QColor(self.factory.header_color) with edit_block(cursor): for i, row in enumerate(tab.items): cell = row.cells[0] if cell.bold: fmt.setFontWeight(QFont.Bold) else: fmt.setFontWeight(QFont.Normal) if i == 0 and hc: c = hc elif (i - 1) % 2 == 0: c = ec else: c = oc if c: fmt.setBackground(c) txt = ''.join([ u'{{:<{}s}}'.format(cell.width).format(cell.text) for cell in row.cells ]) cursor.insertText(txt + '\n', fmt)
currBlock = currBlock.next() # Open the text finder if event.key() == Qt.Key_F and event.modifiers() == Qt.ControlModifier: customKey = True print("Opening finder...") if not customKey: QPlainTextEdit.keyPressEvent(self, event) def initUI(self): pass # Create the font styles that will highlight the code keywordFormat = QTextCharFormat() keywordFormat.setForeground(QColor('blue')) operatorFormat = QTextCharFormat() operatorFormat.setForeground(QColor('red')) braceFormat = QTextCharFormat() braceFormat.setForeground(QColor('darkGray')) defClassFormat = QTextCharFormat() defClassFormat.setForeground(QColor('black')) stringFormat = QTextCharFormat() stringFormat.setForeground(QColor('magenta')) string2Format = QTextCharFormat() string2Format.setForeground(QColor('darkMagenta')) commentFormat = QTextCharFormat() commentFormat.setForeground(QColor('darkGreen')) commentFormat.setFontItalic(True) selfFormat = QTextCharFormat()
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold) cursor.insertText( """ Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText( """ Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText( """ There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1
def __init__(self, parent=None): """ @param parent QObject or QTextDocument or QTextEdit or None """ super(PyHighlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(HLS_KEYWORD_COLOR) keywordFormat.setFontWeight(QFont.Bold) self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in self.KEYWORD_PATTERNS] typeFormat = QTextCharFormat() typeFormat.setForeground(HLS_TYPE_COLOR) typeFormat.setFontWeight(QFont.Bold) self.highlightingRules.extend([(QRegExp(pattern), typeFormat) for pattern in self.TYPE_PATTERNS]) constantFormat = QTextCharFormat() constantFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.extend([(QRegExp(pattern), constantFormat) for pattern in self.CONSTANT_PATTERNS]) classFormat = QTextCharFormat() classFormat.setFontWeight(QFont.Bold) classFormat.setForeground(HLS_CLASS_COLOR) self.highlightingRules.append((QRegExp(r"\bQ[A-Za-z]+\b"), classFormat)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(HLS_FUNCTION_COLOR) self.highlightingRules.append((QRegExp(r"\b[A-Za-z0-9_]+(?=\()"), functionFormat)) quotationFormat = QTextCharFormat() quotationFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.append((QRegExp(r'"[^"]*"'), quotationFormat)) self.highlightingRules.append((QRegExp(r'u"[^"]*"'), quotationFormat)) self.highlightingRules.append((QRegExp(r"'[^']*'"), quotationFormat)) self.highlightingRules.append((QRegExp(r"u'[^']*'"), quotationFormat)) singleLineCommentFormat = QTextCharFormat() singleLineCommentFormat.setForeground(HLS_COMMENT_COLOR) self.highlightingRules.append((QRegExp("#[^\n]*"), singleLineCommentFormat)) self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(HLS_COMMENT_COLOR) self.commentStartExpression = QRegExp(r'"""') self.commentEndExpression = QRegExp(r'"""') todoFormat = QTextCharFormat() todoFormat.setBackground(HLS_TODO_COLOR) self.postHighlightingRules = [(QRegExp(pattern), todoFormat) for pattern in HLS_TODO_PATTERNS] doxyFormat = QTextCharFormat() doxyFormat.setForeground(HLS_COMMENT_COLOR) doxyFormat.setFontWeight(QFont.Bold) self.postHighlightingRules.extend([(QRegExp(pattern), doxyFormat) for pattern in HLS_DOXY_PATTERNS])
def applyFormatting(self): """ TOWRITE """ prefixLength = len(self.prefix) start = -1 stop = -1 formats = [] # QList<QTextLayout.FormatRange> # Bold Prefix formatPrefix = QTextCharFormat() formatPrefix.setFontWeight(QFont.Bold) rangePrefix = QTextLayout.FormatRange() rangePrefix.start = 0 rangePrefix.length = prefixLength rangePrefix.format = formatPrefix formats.append(rangePrefix) # Keywords start = self.prefix.find('[') stop = self.prefix.rfind(']') if (start != -1 & stop != -1 & start < stop): formatKeyword = QTextCharFormat() formatKeyword.setFontWeight(QFont.Bold) formatKeyword.setForeground(QColor("#0095FF")) rangeStart = -1 rangeStop = -1 for i in reversed(range(start, stop + 1)): if self.prefix[i] == ']': rangeStop = i if self.prefix[i] == '[' or self.prefix[i] == '/': rangeStart = i rangeKeyword = QTextLayout.FormatRange() rangeKeyword.start = rangeStart + 1 rangeKeyword.length = rangeStop - rangeStart - 1 rangeKeyword.format = formatKeyword formats.append(rangeKeyword) rangeStop = i # Default Values start = self.prefix.find('{') stop = self.prefix.rfind('}') if start != -1 & stop != -1 & start < stop: formatKeyword = QTextCharFormat() formatKeyword.setFontWeight(QFont.Bold) formatKeyword.setForeground(QColor("#00AA00")) rangeStart = -1 rangeStop = -1 for i in reversed(range(start, stop + 1)): if self.prefix[i] == '}': rangeStop = i if self.prefix[i] == '{': rangeStart = i rangeKeyword = QTextLayout.FormatRange() rangeKeyword.start = rangeStart + 1 rangeKeyword.length = rangeStop - rangeStart - 1 rangeKeyword.format = formatKeyword formats.append(rangeKeyword) rangeStop = i self.changeFormatting(formats)