Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Change the color of an incorrectly entered character in QTextEdit

Change the color of an incorrectly entered character in QTextEdit

Scheduled Pinned Locked Moved Unsolved General and Desktop
qtexteditpyside6colorpython
10 Posts 3 Posters 711 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Devik
    wrote on 22 Apr 2024, 14:20 last edited by
    #1

    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())
    
    1 Reply Last reply
    0
    • S Offline
      S Offline
      SGaist
      Lifetime Qt Champion
      wrote on 22 Apr 2024, 18:45 last edited by
      #2

      Hi and welcome to devnet,

      It looks like you want to implement something similar to QSyntaxHighlighter.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      D 2 Replies Last reply 23 Apr 2024, 05:04
      1
      • S SGaist
        22 Apr 2024, 18:45

        Hi and welcome to devnet,

        It looks like you want to implement something similar to QSyntaxHighlighter.

        D Offline
        D Offline
        Devik
        wrote on 23 Apr 2024, 05:04 last edited by
        #3
        This post is deleted!
        1 Reply Last reply
        0
        • S SGaist
          22 Apr 2024, 18:45

          Hi and welcome to devnet,

          It looks like you want to implement something similar to QSyntaxHighlighter.

          D Offline
          D Offline
          Devik
          wrote on 23 Apr 2024, 06:08 last edited by
          #4

          @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.

          S 1 Reply Last reply 23 Apr 2024, 21:42
          0
          • D Devik
            23 Apr 2024, 06:08

            @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.

            S Offline
            S Offline
            SGaist
            Lifetime Qt Champion
            wrote on 23 Apr 2024, 21:42 last edited by
            #5

            @Devik why would you need to have an additional letter for it to its job ?

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            D 1 Reply Last reply 23 Apr 2024, 22:11
            0
            • S SGaist
              23 Apr 2024, 21:42

              @Devik why would you need to have an additional letter for it to its job ?

              D Offline
              D Offline
              Devik
              wrote on 23 Apr 2024, 22:11 last edited by
              #6

              @SGaist I didn't understand the question

              S 1 Reply Last reply 24 Apr 2024, 20:15
              0
              • D Devik
                23 Apr 2024, 22:11

                @SGaist I didn't understand the question

                S Offline
                S Offline
                SGaist
                Lifetime Qt Champion
                wrote on 24 Apr 2024, 20:15 last edited by
                #7

                @Devik why do you need to enter an additional character for QSyntaxHighlighter to do its job ?

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                D 1 Reply Last reply 28 Apr 2024, 02:29
                0
                • S SGaist
                  24 Apr 2024, 20:15

                  @Devik why do you need to enter an additional character for QSyntaxHighlighter to do its job ?

                  D Offline
                  D Offline
                  Devik
                  wrote on 28 Apr 2024, 02:29 last edited by
                  #8

                  @SGaist I don't know myself, apparently it works like this, that if an incorrect character is entered, you need to enter the next one to make it color.

                  P 1 Reply Last reply 28 Apr 2024, 03:44
                  0
                  • D Devik
                    28 Apr 2024, 02:29

                    @SGaist I don't know myself, apparently it works like this, that if an incorrect character is entered, you need to enter the next one to make it color.

                    P Offline
                    P Offline
                    Pl45m4
                    wrote on 28 Apr 2024, 03:44 last edited by Pl45m4
                    #9

                    @Devik

                    I think @SGaist misunderstood you ;-)
                    He thought you wanted the highlighting to happen on the next letter, like you thought QSyntaxHighlighter does and therefore you can't use it ;-)
                    But this is not the case. The highlighting in QSyntaxHighlighter 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.

                    • https://doc.qt.io/qt-6/qtwidgets-richtext-syntaxhighlighter-example.html

                    If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                    ~E. W. Dijkstra

                    S 1 Reply Last reply 28 Apr 2024, 19:32
                    0
                    • P Pl45m4
                      28 Apr 2024, 03:44

                      @Devik

                      I think @SGaist misunderstood you ;-)
                      He thought you wanted the highlighting to happen on the next letter, like you thought QSyntaxHighlighter does and therefore you can't use it ;-)
                      But this is not the case. The highlighting in QSyntaxHighlighter 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.

                      • https://doc.qt.io/qt-6/qtwidgets-richtext-syntaxhighlighter-example.html
                      S Offline
                      S Offline
                      SGaist
                      Lifetime Qt Champion
                      wrote on 28 Apr 2024, 19:32 last edited by
                      #10

                      @Pl45m4 nope, I understood ;-) I wanted to know why additional letter was needed since it's not how QSyntaxHighlighter works as you correctly explained.

                      Interested in AI ? www.idiap.ch
                      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                      1 Reply Last reply
                      0

                      3/10

                      23 Apr 2024, 05:04

                      topic:navigator.unread, 7
                      • Login

                      • Login or register to search.
                      3 out of 10
                      • First post
                        3/10
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved