Change the color of an incorrectly entered character in QTextEdit
-
I have 2 QTextEdits: textedit is the main one where the user enters text and textedit_bg is the background text from which the user reprints.
It is necessary for the color of the characters to change (for example, to red), which were probably reprinted, and at the same time the symbol of the background text changes (the color does not change). If an incorrectly entered character has been deleted, return everything as it was.
I tried to implement this in the result function, but nothing comes out :(from sys import argv, exit from PySide6.QtCore import * from PySide6.QtGui import * from PySide6.QtWidgets import * from random import shuffle texts = ['Contented you dearest pleased happiness afraid use. Bachelor entirely vanity alone out travelling terms ' 'along. Otherwise open prepared prosperous weddings tastes. Cousin engage knew confined distrusts. Fifteen ' 'around adapted doubtful opinions ten boy introduced merits late those admire.', 'Examine general what calling friends relied precaution highly disposed. Connection ignorant vexed enabled ' 'husbands explained norland strangers morning past. Vexed interested dull listening sitting wise. Voice ' 'newspaper its been improve are hope horrible eldest. Dwelling graceful scarcely very.'] class Window(QMainWindow): def __init__(self, parent=None): super(Window, self).__init__(parent) self.setWindowTitle('TextEdit') self.setMinimumSize(820, 0) self.setMaximumSize(820, 1200) self.centralwidget = QWidget(self) self.centralwidget.setObjectName(u"centralwidget") self.setCentralWidget(self.centralwidget) self.layout = QGridLayout(self.centralwidget) self.layout.setObjectName(u"layout") self.textedit_bg = QTextEdit(self) self.textedit_bg.setObjectName(u"textedit_bg") self.textedit_bg.setStyleSheet(''' #textedit_bg { background-color: #FF7F50; color: #FFFF00; font: 16pt "Lato"; } ''') self.textedit_bg.setWordWrapMode(QTextOption.NoWrap) self.textedit = QTextEdit(self) # !!! lineedit self.textedit.setObjectName(u"textedit") self.textedit.setStyleSheet(''' #textedit { background-color: transparent; color: #0000CD; font: 16pt "Lato"; } ''') self.textedit.setWordWrapMode(QTextOption.NoWrap) self.textedit.cursorPositionChanged.connect(self._change_cursor) self.textedit.selectionChanged.connect(self._change_selection) self.layout.addWidget(self.textedit_bg, 1, 1) self.layout.addWidget(self.textedit, 1, 1) self.button = QPushButton('Create Text', self) self.layout.addWidget(self.button, 2, 1) self.button.clicked.connect(self.capacity) self.textedit_bg.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textedit_bg.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textedit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textedit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textedit_bg.setFixedHeight(132) self.textedit.setFixedHeight(132) self.textedit.setFocus() self.text_res = '' self.index = 0 self.textedit.textChanged.connect(self.result) def result(self): text = self.textedit.toPlainText() text_bg = self.textedit_bg.toPlainText().split('\n')[0] if 0 < len(text) < len(text_bg): if text_bg[len(text) - 1] != text[-1]: pass def capacity(self): if not self.text_res: self.text_res = self.get_texts() if self.index == len(self.text_res) - 4: for i in self.text_res[:self.index]: self.text_res.remove(i) self.text_res += self.get_texts() self.index = 0 text = '\n'.join(self.text_res[self.index:self.index + 4]) self.textedit_bg.setText(text) self.index += 1 def get_texts(self): shuffle(texts) result = [] for i, item in enumerate(texts): lst = [] for w in item.split(): if 787 < self.__get_pixels_wide(' '.join(lst + [w])): result.append(lst) lst = [] lst.append(w) result.append(lst) return list(map(' '.join, result)) def _change_cursor(self): cursor = self.textedit.textCursor() if cursor.positionInBlock() < len(self.textedit.document().toPlainText()): cursor.movePosition(QTextCursor.End) self.textedit.setTextCursor(cursor) def _change_selection(self): cursor = self.textedit.textCursor() cursor.clearSelection() self.textedit.setTextCursor(cursor) def __get_pixels_wide(self, words): return self.textedit_bg.fontMetrics().boundingRect(words).width() if __name__ == "__main__": app = QApplication(argv) window = Window() window.show() exit(app.exec())
-
Hi and welcome to devnet,
It looks like you want to implement something similar to QSyntaxHighlighter.
-
@SGaist I tried to use this class, but the problem is that it does not work immediately. For example, if an incorrect character is entered, in order for it to be highlighted, you need to enter the next one, and I need the color to change immediately when I enter it.
-
I think @SGaist misunderstood you ;-)
He thought you wanted the highlighting to happen on the next letter, like you thoughtQSyntaxHighlighter
does and therefore you can't use it ;-)
But this is not the case. The highlighting inQSyntaxHighlighter
happens immediately. On the last letter of the recognized word/match.Check out the example:
(The matches are words like "void", "class", "typedef", etc)
They turn blue and bold as soon as you put in the last letter.