2013-10-07 61 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)