向在QLineEdit中输入的部分文本添加语法突出显示

时间:2018-11-03 01:18:42

标签: python python-2.7 user-interface pyside qlineedit

使用PySide / PyQT,我需要在QLineEdit中输入的文本中添加一些语法突出显示。我需要突出显示特定的关键字。

我在下面的文章中看到了一个示例,该示例说明了如何在C ++中执行此操作,但我正在尝试在Python中执行此操作。 (尝试将C ++转换为Python,但无法获取...)有人对如何在Python中执行此操作有建议吗?谢谢。

How can I change color of part of the text in QLineEdit?

更多信息:

当前,我正在如下更改整个QLineEdit的颜色:

for dupLineEd in duplicates[1]:
    dupLineEd.setStyleSheet("QLineEdit{color:Khaki}")

这不是理想的。我需要做的是确定QLineEdit中的某些单词是否满足条件(在这种情况下,它们是否与另一个QLineEdit中的单词重复),如果是,则仅用颜色突出显示QLineEdit中的单词,而不是整个QLineEdit。该突出显示需要在用户键入时实时完成,以便例如在他们完成一个单词时,如果该单词符合条件,则该单词会变成黄色。 QLineEdit中的其余文本不会更改颜色。

在此先感谢任何有建议的人!

1 个答案:

答案 0 :(得分:0)

到目前为止,我能找到的最好的解决方法是制作一个新的QTextEdit类,其行为(部分)类似于QLineEdit。

现在我要借用由igor-bogomolov编写的QligEdit的Highligter类,该类发布在github上: https://github.com/pyside/Examples/blob/master/examples/richtext/syntaxhighlighter/syntaxhighlighter.py

我得到的功能代码如下。 (您需要根据您的环境定义main_window。)

class qTextEditTestUI(QtGui.QDialog):

    def __init__(self, parent=QtGui.QWidget):
        # Inherit __init__
        super(qTextEditTestUI, self).__init__(parent)


        # Set object name and window title
        self.setObjectName('qTextEditTestWindow')
        self.setWindowTitle('qTextEdit Test Window')

        # Window type (Qt.tool not Qt.Window)
        self.setWindowFlags(QtCore.Qt.Tool)


        # ATTRS

        self.highlighter = Highlighter()

        # CREATE WIDGETS

        variableFormat = QtGui.QTextCharFormat()
        #variableFormat.setFontWeight(QtGui.QFont.Bold)
        variableFormat.setForeground(QtGui.QColor('Khaki'))
        self.highlighter.addMapping('hello', variableFormat)


        # Make a TextEdit
        self.QTextEd = snglLnQTextEdit()

        # Add the TextEdit's document to the highlighter
        self.highlighter.addToDocument(self.QTextEd.document())


        # SET MASTER LAYOUT
        masterLayout = QtGui.QVBoxLayout()
        self.setLayout(masterLayout)

        # MASTER LAYOUT
        masterLayout.addWidget(self.QTextEd)
        masterLayout.addStretch()


## QLineEdit-Like QTextEdit
class snglLnQTextEdit(QtGui.QTextEdit):
    def __init__(self, parent=None):
        QtGui.QTextEdit.__init__(self, parent)

        QTextEdFontMetrics =  QtGui.QFontMetrics(self.font())
        self.QTextEdRowHeight = QTextEdFontMetrics.lineSpacing()
        self.setFixedHeight(2 * self.QTextEdRowHeight)
        self.setLineWrapMode(QtGui.QTextEdit.NoWrap)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        # CONNECT WIDGET SIGNAL
        self.textChanged.connect(self.validateCharacters)

    def validateCharacters(self):
        badChars = ['\n']
        cursor = self.textCursor()
        curPos = cursor.position()
        for badChar in badChars:
            origText = self.toPlainText()
            for char in origText:
                if char in badChars:
                    cleanText = origText.replace(char, '')
                    self.blockSignals(True)
                    self.setText(cleanText)
                    self.blockSignals(False)
                    cursor.setPosition(curPos-1)
        self.setTextCursor(cursor)

## Highligher Class written by igor-bogomolov
class Highlighter(QtCore.QObject):
    def __init__(self, parent=None):
        QtCore.QObject.__init__(self, parent)

        self.mappings = {}

    def addToDocument(self, doc):
        self.connect(doc, QtCore.SIGNAL('contentsChange(int, int, int)'), self.highlight)

    def addMapping(self, pattern, format):
        self.mappings[pattern] = format

    def highlight(self, position, removed, added):
        doc = self.sender()

        block = doc.findBlock(position)
        if not block.isValid():
            return

        if added > removed:
            endBlock = doc.findBlock(position + added)
        else:
            endBlock = block

        while block.isValid() and not (endBlock < block):
            self.highlightBlock(block)
            block = block.next()

    def highlightBlock(self, block):
        layout = block.layout()
        text = block.text()

        overrides = []

        for pattern in self.mappings:
            for m in re.finditer(pattern,text):
                range = QtGui.QTextLayout.FormatRange()
                s,e = m.span()
                range.start = s
                range.length = e-s
                range.format = self.mappings[pattern]
                overrides.append(range)

        layout.setAdditionalFormats(overrides)
        block.document().markContentsDirty(block.position(), block.length())


## Test Usage:

panl = qTextEditTestUI(parent=main_window())
panl.show()

这可以完成工作,但是我对此并不完全满意;感觉笨拙。我仍然希望弄清楚如何使用QLineEdit进行这种突出显示。