Solved How do you replace text using python qscintilla editor widget?
-
Here is a broken MWE. It replaces
\nat
withNN
when it starts up, but when you type text it starts entering the text backwards.Was wondering if there was a recipe for replacing text that replaces only the substring and not the whole document.
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.Qsci import * import re NAT = re.compile(r"\\nat") class MyLexer(QsciLexerCustom): def __init__(self, parent): super(MyLexer, self).__init__(parent) def language(self): return "SimpleLanguage" def description(self, style): return "" def styleText(self, start, end): self.startStyling(start) editor = self.parent() text = editor.text()[start:end] text = NAT.sub('NN', text) editor.SendScintilla(editor.SCI_SETTEXT, text.encode('utf-8')) myCodeSample = r""" \nat """.replace("\n","\r\n") class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__editor = QsciScintilla() self.__editor.setText(myCodeSample) # 'myCodeSample' is a string containing some C-code self.__editor.setLexer(None) # We install lexer later self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__lexer = MyLexer(self.__editor) self.__editor.setLexer(self.__lexer) self.__lyt.addWidget(self.__editor) self.show() def __btn_action(self): print("Hello World!") if __name__ == '__main__': app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Fusion')) myGUI = CustomMainWindow() sys.exit(app.exec_())
Have you solved this problem before? If so, please let me have the recipe :)
-
def styleText(self, start, end): self.startStyling(start) editor = self.parent() #text = editor.text()[start:end] editor.findFirst(NAT.pattern, True, False, False, True) editor.replace('NN')
I figured it out by RTFM here: https://www.riverbankcomputing.com/static/Docs/QScintilla/classQsciScintilla.html
It does search the whole document, but I don't care since it's written in C++.