2013-10-07 6 views
1

Я хочу выделить слово в показанном тексте, показанном в QTextEdit из PySide, и я нахожу this answer для PyQt неплохим и работоспособным, но он не работает с QTextEdit от PySide.Выделение текста в 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' и ничего больше. Итак, как именно «не работает»? Можете ли вы показать код? –

+0

Я знаю, что они очень похожи друг на друга, но в этом я думаю, что что-то совершенно другое. Я добавляю код, спасибо – Haiku

ответ

1

я узнал, что в PySide метод movePosition нужны 3 argumnets и код будет правильным, если этот метод выглядит следующим образом:

cursor.movePosition(QtGui.QTextCursor.EndOfWord, QtGui.QTextCursor.KeepAnchor, 1) 
Смежные вопросы