2013-10-07 124 views
1

我想突出显示在PySide的QTextEdit中显示的文本中的单词,并且我发现PyQt的this answer相当不错并且工作良好,但它不适用于来自PySide的QTextEdit。在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它停止高亮的话。

+0

PySide与PyQt的应该是怎么样的API的工作原理几乎相同。很多情况下,在很多情况下,您可以更改'import'行,而不是其他任何东西。那么,它究竟是如何“不工作”?你能显示一些代码吗? – 2013-10-07 23:04:16

+0

我知道他们是非常相似的,但在这一个我认为是完全不同的东西。我添加了代码,谢谢 – Haiku

回答

1

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

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