【问题标题】:Highlighting text in PySide.QTextEdit在 PySide.QTextEdit 中突出显示文本
【发布时间】:2013-10-11 23:55:39
【问题描述】:

我想突出显示在 PySide 的 QTextEdit 中显示的文本中的一个单词,我发现 PyQt 的 this answer 非常好并且有效,但它不适用于 PySide 的 QTextEdit。

有人知道 PySide 有什么问题吗?

这是我上面提到的答案中的代码:

from PyQt4 import QtGui
from PyQt4 import QtCore

class MyHighlighter(QtGui.QTextEdit):
    def __init__(self, parent=None):
        super(MyHighlighter, self).__init__(parent)
        # Setup the text editor
        text = """In this text I want to highlight this word and only this word.\n""" +\
        """Any other word shouldn't be highlighted"""
        self.setText(text)
        cursor = self.textCursor()
        # Setup the desired format for matches
        format = QtGui.QTextCharFormat()
        format.setBackground(QtGui.QBrush(QtGui.QColor("red")))
        # Setup the regex engine
        pattern = "word"
        regex = QtCore.QRegExp(pattern)
        # Process the displayed document
        pos = 0
        index = regex.indexIn(self.toPlainText(), pos)
        while (index != -1):
            # Select the matched text and apply the desired format
            cursor.setPosition(index)
            cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
            cursor.mergeCharFormat(format)
            # Move to the next match
            pos = index + regex.matchedLength()
            index = regex.indexIn(self.toPlainText(), pos)

if __name__ == "__main__":
    import sys
    a = QtGui.QApplication(sys.argv)
    t = MyHighlighter()
    t.show()
    sys.exit(a.exec_())

它完全适用于 PyQt,但是当我将导入更改为 PySide 时,它​​会停止突出显示单词。

【问题讨论】:

  • PySide 和 PyQT 在 API 的工作方式上应该几乎相同。如此之多,以至于在许多情况下,您可以更改 import 行,仅此而已。那么,它究竟是如何“不工作”的呢?你能显示一些代码吗?
  • 我知道它们彼此非常相似,但在这一点上,我认为有些东西完全不同。我添加代码,谢谢

标签: python-3.x pyside


【解决方案1】:

我发现在 PySide 中的方法 movePosition 需要 3 个参数,如果这个方法是这样的,代码将是正确的:

cursor.movePosition(QtGui.QTextCursor.EndOfWord, QtGui.QTextCursor.KeepAnchor, 1)

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 2021-01-15
    • 2013-01-26
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多