如何更改空白字符的颜色?

时间:2019-07-04 02:17:47

标签: python pyside2 qtextedit

我正在使用Qt和Python(PySide2)创建文本编辑器。像大多数其他文本编辑器一样,我想创建可见的空格(空格,制表符,换行...)并使其成功。 QTextEdit和QTextOption将空格字符显示为可见的特殊字符。 (空格到点,制表符到箭头,新行到反向P)

但是这些特殊字符的颜色与其他字符相同。我认为,如果颜色不同,它将更具可读性。

如何更改空格特殊字符的颜色?

{
"value1": 1,
"value2": 2,
"value3": 3,
.
.
.
and so on..
}

2 个答案:

答案 0 :(得分:1)

如果要根据文本提供特殊内容,则应使用QSyntaxHighlighter。为此,您必须获取模式的开始和结束,并使用setFormat()更改格式。

我只能修改空格(" ")和制表符("\t")的格式,而不能修改段落分隔符():

import re
from PySide2 import QtCore, QtGui, QtWidgets


orgText = """
\t\tAll those moments
\t\twill be lost
  in time
  like tears
in rain.
       It's time to die."""


class Highlighter(QtGui.QSyntaxHighlighter):
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        space_format = QtGui.QTextCharFormat()
        space_format.setBackground(QtGui.QColor("salmon"))

        tab_format = QtGui.QTextCharFormat()
        tab_format.setBackground(QtGui.QColor("lightgray"))

        self.highlightingRules = [
            (r"( )\1*", space_format),
            (r"(\t)\1*", tab_format),
        ]

    def highlightBlock(self, text):
        for pattern, fmt in self.highlightingRules:
            expression = re.compile(pattern)
            m = expression.search(text)
            while m is not None:
                start, end = m.span()
                self.setFormat(start, end - start, fmt)
                m = expression.search(text, end + 1)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.teOrg = QtWidgets.QTextEdit()
        self.setCentralWidget(self.teOrg)

        self.teOrg.setPlainText(orgText)

        option = QtGui.QTextOption()
        option.setFlags(
            QtGui.QTextOption.ShowTabsAndSpaces
            | QtGui.QTextOption.ShowLineAndParagraphSeparators
        )
        self.teOrg.document().setDefaultTextOption(option)
        self.highlighter = Highlighter(self.teOrg.document())


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())

enter image description here

答案 1 :(得分:1)

最后,我重写了@eyllanesc的代码。

import sys
import typing
import re

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets


class SyntaxHighlighter(QtGui.QSyntaxHighlighter):
  def __init__(self, parent:typing.Union[QtCore.QObject, QtGui.QTextDocument, None]=None):
    super().__init__(parent)
    self.spaceFmt = QtGui.QTextCharFormat()
    self.spaceFmt.setForeground(QtGui.QColor('red'))
    self.expression = re.compile(r'\s+', re.U | re.S | re.M)


  def highlightBlock(self, text:str):
    for match in self.expression.finditer(text):
      start, end = match.span()
      self.setFormat(start, end - start, self.spaceFmt)


class TextEditWin(QtWidgets.QMainWindow):
  def __init__(self):
    # Initialize ui.
    super().__init__()
    self.resize(800, 600)
    self.textEdit = QtWidgets.QTextEdit(self)
    self.setCentralWidget(self.textEdit)
    self.textEdit.setFontPointSize(15)

    # Make space characters visible.
    option = QtGui.QTextOption()
    option.setFlags(QtGui.QTextOption.ShowTabsAndSpaces | QtGui.QTextOption.ShowLineAndParagraphSeparators)
    self.textEdit.document().setDefaultTextOption(option)

    # Change color of space characters.
    self.highlighter = SyntaxHighlighter(self.textEdit.document())


if __name__ == '__main__':
  app = QtWidgets.QApplication(sys.argv)
  win = TextEditWin()
  win.show()
  sys.exit(app.exec_())

我的代码也不会更改段落分隔符(¶)的颜色。我认为这是因为Qt会在调用highlightBlock()时传递除“ \ n”之外的文本。

感谢@eyllanesc。