Python源码示例:PyQt5.QtGui.QTextCharFormat()
示例1
def _get_format_from_style(self, token, style):
""" Returns a QTextCharFormat for token by reading a Pygments style.
"""
result = QtGui.QTextCharFormat()
for key, value in list(style.style_for_token(token).items()):
if value:
if key == 'color':
result.setForeground(self._get_brush(value))
elif key == 'bgcolor':
result.setBackground(self._get_brush(value))
elif key == 'bold':
result.setFontWeight(QtGui.QFont.Bold)
elif key == 'italic':
result.setFontItalic(True)
elif key == 'underline':
result.setUnderlineStyle(
QtGui.QTextCharFormat.SingleUnderline)
elif key == 'sans':
result.setFontStyleHint(QtGui.QFont.SansSerif)
elif key == 'roman':
result.setFontStyleHint(QtGui.QFont.Times)
elif key == 'mono':
result.setFontStyleHint(QtGui.QFont.TypeWriter)
return result
示例2
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
# Syntax styles that can be shared by all languages
示例3
def _get_format_from_style(self, token, style):
""" Returns a QTextCharFormat for token by reading a Pygments style.
"""
result = QtGui.QTextCharFormat()
for key, value in style.style_for_token(token).items():
if value:
if key == 'color':
result.setForeground(self._get_brush(value))
elif key == 'bgcolor':
result.setBackground(self._get_brush(value))
elif key == 'bold':
result.setFontWeight(QtGui.QFont.Bold)
elif key == 'italic':
result.setFontItalic(True)
elif key == 'underline':
result.setUnderlineStyle(
QtGui.QTextCharFormat.SingleUnderline)
elif key == 'sans':
result.setFontStyleHint(QtGui.QFont.SansSerif)
elif key == 'roman':
result.setFontStyleHint(QtGui.QFont.Times)
elif key == 'mono':
result.setFontStyleHint(QtGui.QFont.TypeWriter)
return result
示例4
def set_bytes(self, bs):
with DisableUpdates(self.textedit):
self.pretty_mode = False
self.data = bs
chunks = HextEditor._split_by_printables(bs)
self.clear()
cursor = QTextCursor(self.textedit.document())
cursor.beginEditBlock()
try:
cursor.select(QTextCursor.Document)
cursor.setCharFormat(QTextCharFormat())
cursor.clearSelection()
for chunk in chunks:
if chr(chunk[0]) in qtprintable:
cursor.insertText(chunk.decode())
else:
for b in chunk:
self._insert_byte(cursor, b)
finally:
cursor.endEditBlock()
self.repaint() # needed to fix issue with py2app
示例5
def highlight(self):
""" Apply text highlighting to current file.
Highlight text of selected case with red underlining.
#format_.setForeground(QtGui.QColor("#990000")) """
if self.selected_file is None:
return
if self.selected_file['fulltext'] is None:
return
format_ = QtGui.QTextCharFormat()
cursor = self.ui.textBrowser.textCursor()
for item in self.case_text:
try:
cursor.setPosition(int(item['pos0']), QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(int(item['pos1']), QtGui.QTextCursor.KeepAnchor)
format_.setFontUnderline(True)
format_.setUnderlineColor(QtCore.Qt.red)
cursor.setCharFormat(format_)
except:
msg = "highlight, text length " + str(len(self.ui.textBrowser.toPlainText()))
msg += "\npos0:" + str(item['pos0']) + ", pos1:" + str(item['pos1'])
logger.debug(msg)
示例6
def highlight(self, fid, textEdit):
""" Add coding and annotation highlights. """
cur = self.app.conn.cursor()
sql = "select pos0,pos1 from annotation where fid=? union all select pos0,pos1 from code_text where fid=?"
cur.execute(sql, [fid, fid])
annoted_coded = cur.fetchall()
format_ = QtGui.QTextCharFormat()
format_.setFontFamily(self.app.settings['font'])
format_.setFontPointSize(self.app.settings['fontsize'])
# remove formatting
cursor = textEdit.textCursor()
cursor.setPosition(0, QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(len(textEdit.toPlainText()), QtGui.QTextCursor.KeepAnchor)
cursor.setCharFormat(format_)
# add formatting
for item in annoted_coded:
cursor.setPosition(int(item[0]), QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(int(item[1]), QtGui.QTextCursor.KeepAnchor)
format_.setFontUnderline(True)
format_.setUnderlineColor(QtCore.Qt.red)
cursor.setCharFormat(format_)
示例7
def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token in self._formats:
return self._formats[token]
result = self._get_format_from_style(token, self._style)
self._formats[token] = result
return result
示例8
def __init__(self, parent=None):
super(Highlighter, self).__init__(parent)
keywordFormat = QtGui.QTextCharFormat()
keywordFormat.setForeground(QtCore.Qt.blue)
keywordFormat.setFontWeight(QtGui.QFont.Bold)
keywordPatterns = ["\\b{}\\b".format(k) for k in keyword.kwlist]
self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat)
for pattern in keywordPatterns]
classFormat = QtGui.QTextCharFormat()
classFormat.setFontWeight(QtGui.QFont.Bold)
self.highlightingRules.append((QtCore.QRegExp("\\bQ[A-Za-z]+\\b"),
classFormat))
singleLineCommentFormat = QtGui.QTextCharFormat()
singleLineCommentFormat.setForeground(QtCore.Qt.gray)
self.highlightingRules.append((QtCore.QRegExp("#[^\n]*"),
singleLineCommentFormat))
quotationFormat = QtGui.QTextCharFormat()
quotationFormat.setForeground(QtCore.Qt.darkGreen)
self.highlightingRules.append((QtCore.QRegExp("\".*\""),
quotationFormat))
self.highlightingRules.append((QtCore.QRegExp("'.*'"),
quotationFormat))
示例9
def update_preview(self):
cursor = self.parent.previewView.textCursor()
cursor.setPosition(0)
cursor.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)
# TODO
# Other kinds of text markup
previewCharFormat = QtGui.QTextCharFormat()
if self.foregroundCheck.isChecked():
previewCharFormat.setForeground(self.foregroundColor)
highlight = QtCore.Qt.transparent
if self.highlightCheck.isChecked():
highlight = self.highlightColor
previewCharFormat.setBackground(highlight)
font_weight = QtGui.QFont.Normal
if self.boldCheck.isChecked():
font_weight = QtGui.QFont.Bold
previewCharFormat.setFontWeight(font_weight)
if self.italicCheck.isChecked():
previewCharFormat.setFontItalic(True)
if self.underlineCheck.isChecked():
previewCharFormat.setFontUnderline(True)
previewCharFormat.setUnderlineColor(self.underlineColor)
previewCharFormat.setUnderlineStyle(
self.underline_styles[self.underlineType.currentText()])
previewCharFormat.setFontStyleStrategy(
QtGui.QFont.PreferAntialias)
cursor.setCharFormat(previewCharFormat)
cursor.clearSelection()
self.parent.previewView.setTextCursor(cursor)
示例10
def __init__(self):
self.annotation_type = None
self.annotation_components = None
self.underline_styles = {
'Solid': QtGui.QTextCharFormat.SingleUnderline,
'Dashes': QtGui.QTextCharFormat.DashUnderline,
'Dots': QtGui.QTextCharFormat.DotLine,
'Wavy': QtGui.QTextCharFormat.WaveUnderline}
示例11
def clear_annotations(self):
if not self.are_we_doing_images_only:
cursor = self.pw.textCursor()
cursor.setPosition(0)
cursor.movePosition(
QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)
previewCharFormat = QtGui.QTextCharFormat()
previewCharFormat.setFontStyleStrategy(
QtGui.QFont.PreferAntialias)
cursor.setCharFormat(previewCharFormat)
cursor.clearSelection()
self.pw.setTextCursor(cursor)
示例12
def __init__(self, text_color=Qt.white, font=QtGui.QFont.DemiBold):
super(_StandardTextFormat, self).__init__()
self.setFontWeight(font)
self.setForeground(text_color)
self.setFontPointSize(13)
self.setVerticalAlignment(QtGui.QTextCharFormat.AlignMiddle)
# TODO: see `QTextEdit.setAlignment` for setting the time to the right
示例13
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
示例14
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
# Syntax styles
示例15
def font(self, family):
format = QtGui.QTextCharFormat()
format.setFontFamily(family)
self.MergeFormat(format)
示例16
def PointSize(self, size):
puntos = int(size)
if puntos > 0:
format = QtGui.QTextCharFormat()
format.setFontPointSize(puntos)
self.MergeFormat(format)
示例17
def Negrita(self):
format = QtGui.QTextCharFormat()
if self.actionNegrita.isChecked():
format.setFontWeight(QtGui.QFont.Bold)
else:
format.setFontWeight(QtGui.QFont.Normal)
self.MergeFormat(format)
示例18
def Cursiva(self):
format = QtGui.QTextCharFormat()
format.setFontItalic(self.actionCursiva.isChecked())
self.MergeFormat(format)
示例19
def Subrayado(self):
format = QtGui.QTextCharFormat()
format.setFontUnderline(self.actionSubrayado.isChecked())
self.MergeFormat(format)
示例20
def Superindice(self):
if self.actionSubScript.isChecked():
self.actionSubScript.blockSignals(True)
self.actionSubScript.setChecked(False)
self.actionSubScript.blockSignals(False)
format = QtGui.QTextCharFormat()
if self.actionSuperScript.isChecked():
format.setVerticalAlignment(QtGui.QTextCharFormat.AlignSuperScript)
else:
format.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)
self.MergeFormat(format)
示例21
def Subindice(self):
if self.actionSuperScript.isChecked():
self.actionSuperScript.blockSignals(True)
self.actionSuperScript.setChecked(False)
self.actionSuperScript.blockSignals(False)
format = QtGui.QTextCharFormat()
if self.actionSubScript.isChecked():
format.setVerticalAlignment(QtGui.QTextCharFormat.AlignSubScript)
else:
format.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)
self.MergeFormat(format)
示例22
def updateUI(self):
"""Update button status when cursor move"""
self.fontComboBox.setCurrentIndex(self.fontComboBox.findText(
self.notas.fontFamily()))
self.FontColor.setPalette(QtGui.QPalette(self.notas.textColor()))
self.FontSize.setCurrentIndex(self.FontSize.findText(
str(int(self.notas.fontPointSize()))))
self.actionNegrita.setChecked(
self.notas.fontWeight() == QtGui.QFont.Bold)
self.actionCursiva.setChecked(self.notas.fontItalic())
self.actionSubrayado.setChecked(self.notas.fontUnderline())
format = self.notas.currentCharFormat()
self.actionTachado.setChecked(format.fontStrikeOut())
self.actionSuperScript.setChecked(False)
self.actionSubScript.setChecked(False)
if format.verticalAlignment() == QtGui.QTextCharFormat.AlignSuperScript:
self.actionSuperScript.setChecked(True)
elif format.verticalAlignment() == QtGui.QTextCharFormat.AlignSubScript:
self.actionSubScript.setChecked(True)
self.actionAlinearIzquierda.setChecked(
self.notas.alignment() == QtCore.Qt.AlignLeft)
self.actionCentrar.setChecked(
self.notas.alignment() == QtCore.Qt.AlignHCenter)
self.actionJustificar.setChecked(
self.notas.alignment() == QtCore.Qt.AlignJustify)
self.actionAlinearDerecha.setChecked(
self.notas.alignment() == QtCore.Qt.AlignRight)
示例23
def colordialog(self):
"""Show dialog to choose font color"""
dialog = QtWidgets.QColorDialog(self.notas.textColor(), self)
if dialog.exec_():
self.FontColor.setPalette(QtGui.QPalette(dialog.currentColor()))
self.notas.setTextColor(dialog.currentColor())
format = QtGui.QTextCharFormat()
format.setForeground(dialog.currentColor())
self.MergeFormat(format)
示例24
def __init__(self, textFormat: Optional[Union[QTextCharFormat, Sequence[QTextCharFormat]]] = None,
matchPattern: Optional[QRegularExpression] = None) -> None:
"""
:param textFormat: Text format of text mathched by pattern
:param matchPattern: Regex pattern to match wanted text
"""
super().__init__(None)
self._text_format = textFormat
self._match_pattern = matchPattern
示例25
def text_format(self) -> Union[QTextCharFormat, Sequence[QTextCharFormat], None]:
return self._text_format
示例26
def _setFormat(self, start: int, length: int, text_format: QTextCharFormat) -> None:
self.setFormat(
start,
length,
text_format
)
示例27
def _setupFormat(self, color: QColor, fontSettings: QFont, colorIsForeground: bool = True) -> QTextCharFormat:
pattern_format = QTextCharFormat()
if color and colorIsForeground:
pattern_format.setForeground(color)
if color and (not colorIsForeground):
pattern_format.setBackground(color)
pattern_format.setFontItalic(fontSettings.italic())
pattern_format.setFontWeight(fontSettings.bold())
return pattern_format
示例28
def _setupFormat(self, color: QColor) -> QTextCharFormat:
pattern_format = QTextCharFormat()
if color is not None:
pattern_format.setForeground(color)
pattern_format.setFontItalic(self._target.property("font").italic())
pattern_format.setFontWeight(self._target.property("font").bold())
return pattern_format
示例29
def fmt(color):
"""
Return a QTextCharFormat with the given attributes.
"""
_color = QtGui.QColor()
_color.setNamedColor(color)
_format = QtGui.QTextCharFormat()
_format.setForeground(_color)
return _format
示例30
def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token in self._formats:
return self._formats[token]
result = self._get_format_from_style(token, self._style)
self._formats[token] = result
return result