3

I want to highlight a word in a text shown that is shown in a QTextEdit of PySide and I find this answer for PyQt quite good and working but it's not working on the QTextEdit from PySide.

Does anyone know what's the problem in here with PySide?

This is the code from the answer I mentioned above:

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_())

It completely works with PyQt but when I change the imports to PySide it stops highlighting words.

Community
  • 1
  • 1
H4iku
  • 674
  • 2
  • 6
  • 23
  • PySide and PyQT should be almost identical in how their APIs work. So much so, that in many cases you can change the `import` line and nothing else. So, how exactly is it "not working"? Can you show some code? –  Oct 07 '13 at 23:04
  • I know they are very similar to each other, but in this one I think something is completely different. I add the code, Thanks – H4iku Oct 08 '13 at 06:10

1 Answers1

2

I found out that in PySide the method movePosition needs 3 argumnets and the code will be correct if this method goes like this:

cursor.movePosition(QtGui.QTextCursor.EndOfWord, QtGui.QTextCursor.KeepAnchor, 1)
H4iku
  • 674
  • 2
  • 6
  • 23