Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. qtextedit settext/setmarkdown not updating
QtWS25 Last Chance

qtextedit settext/setmarkdown not updating

Scheduled Pinned Locked Moved Unsolved Qt for Python
6 Posts 3 Posters 1.7k 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.
  • H Offline
    H Offline
    hermes
    wrote on last edited by
    #1

    Dear all,

    Once again, I'm stuck and would like to ask for your advice concerning an issue with qtextedit.
    I have a qtextedit widget and can at initialization write text A to it with settext (or setMarkdown at 5.14). So far this works nicely.
    Next to the qtextedit, I have a Qtreeview filled by QfilesystemModel. When the user selects a new file B, I want the qtextedit to be updated. The connection to the selectionchanged event works and settext is called on the qtextedit.
    The problem: The text is not updated. Only if I select yet another file "C", the previous selected file (B) is shown.
    I found online some pages mentioninga similar issue claiming to use qthreads (which does not match my usecase) or to call qapplication.processevents, which does not help either...

    Any clues?
    Any hints are apprechiated!

    Ulrich

    python on windows 10 qt5.14

    1 Reply Last reply
    0
    • Christian EhrlicherC Online
      Christian EhrlicherC Online
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @hermes said in qtextedit settext/setmarkdown not updating:

      event works and settext is called on the qtextedit.

      How? Please show us some code.

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      1 Reply Last reply
      1
      • H Offline
        H Offline
        hermes
        wrote on last edited by
        #3

        Sorry,... the basic mistake...
        It's ugly, but only my start...

        to execute it:
        python.exe .\mynotes.py ..\test-file\ test.md
        where
        mynnotes.py is the file with the following code.
        ..\test-file\ is a folder with markdown or textfiles
        test.md is the first file it should show.

        import sys, os, re
        from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout, QHBoxLayout, QMainWindow
        from PyQt5.QtGui import QIcon, QFont, QImage, QTextDocument
        from PyQt5 import QtCore, QtGui, QtWidgets
        from PyQt5.QtCore import PYQT_VERSION_STR
        
        IMAGE_EXTENSIONS = ['.jpg','.png','.bmp']
        
        def splitext(p):
            return os.path.splitext(p)[1].lower()
        
        class TextEdit(QtWidgets.QTextEdit):
        
            def canInsertFromMimeData(self, source):
        
                if source.hasImage():
                    return True
                else:
                    return super(TextEdit, self).canInsertFromMimeData(source)
        
            def insertFromMimeData(self, source):
        
                cursor = self.textCursor()
                document = self.document()
        
                if source.hasUrls():
        
                    for u in source.urls():
                        file_ext = splitext(str(u.toLocalFile()))
                        if u.isLocalFile() and file_ext in IMAGE_EXTENSIONS:
                            image = QImage(u.toLocalFile())
                            document.addResource(QTextDocument.ImageResource, u, image)
                            cursor.insertImage(u.toLocalFile())
        
                        else:
                            # If we hit a non-image or non-local URL break the loop and fall out
                            # to the super call & let Qt handle it
                            break
        
                    else:
                        # If all were valid images, finish here.
                        return
        
                elif source.hasImage():
                    image = source.imageData()
                    uuid = hexuuid()
                    document.addResource(QTextDocument.ImageResource, uuid, image)
                    cursor.insertImage(uuid)
                    return
        
                super(TextEdit, self).insertFromMimeData(source)
        
        class window(QMainWindow):
            def __init__(self):
                super().__init__()
        
            def treeselectionChanged(self, selected, deselected):
                filename = self.model.filePath(selected.indexes()[0])
                if os.path.isfile(filename) and filename != self.c_file:
                    self.savefile()
                    print('changing file to ', filename)
                    self.loadfile(filename)
                    self.c_file = filename
        
            def settext(self, c_text):
                qt_subversion = int(re.match('5\.(\d*)',PYQT_VERSION_STR).group(1))
                if qt_subversion >= 14:
                    self.textedit.setMarkdown(c_text)
                    # to automatttically change some formatting, e.g. * to bulleted list
                    #self.textedit.setAutoFormatting(QtWidgets.QTextEdit.AutoAll)
                else:
                    self.textedit.setText(c_text)
                return True
        
            def savefile(self):
                """saves the current qtextedit content to file"""
                #save the old file
                out = self.textedit.toMarkdown()
                tmp = open(self.filename,'w')
                tmp.write(out)
                tmp.close()
                
            def loadfile(self, filename):
                c_text = open(self.c_file, 'r').read()
                self.settext(c_text)
                self.filename = filename
                self.setWindowTitle(os.path.basename(filename))
                print('new file loaded: ', filename)
                return True 
            
        
            def eventFilter(self, obj, event):
                if event.type() == QtCore.QEvent.KeyPress and obj is self.textedit:
                    if event.key() == QtCore.Qt.Key_Return and self.textedit.hasFocus():
                        self.textedit.setMarkdown(self.textedit.toMarkdown())
                return super().eventFilter(obj, event)
        
            def closeEvent(self, event):
                """" called if program is closed, to save the current file"""
                self.savefile()
                
            def createUI(self, basepath, filename):
                self.centralwidget = QWidget()
                self.windowLayout = QHBoxLayout()
                
                self.c_file = os.path.join(basepath, filename)
        
                # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        
                # the left  side of the file viewer
                self.model = QFileSystemModel()
                root = self.model.setRootPath(basepath)
                self.model.setNameFilters(['*.md'])
                self.model.setNameFilterDisables(False)
                self.tree = QTreeView()
                self.tree.setModel(self.model)
                self.tree.setRootIndex(root)
                self.tree.setColumnHidden(1, True)
                self.tree.setColumnHidden(2, True)
                self.tree.setColumnHidden(3, True)
                self.tree.setAnimated(False)
                self.tree.setIndentation(20)
                self.tree.setSortingEnabled(True)
                self.tree.setWindowTitle("Dir View")
                self.tree.resize(640, 480)
                self.tree.selectionModel().selectionChanged.connect(self.treeselectionChanged)
                self.windowLayout.addWidget(self.tree)
        
                # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        
                # the edit window on the left side
                self.textedit = TextEdit()
                self.loadfile(self.c_file)
                self.windowLayout.addWidget(self.textedit)
        
                # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                self.centralwidget.setLayout(self.windowLayout)
                self.setCentralWidget(self.centralwidget)
                self.show()
        
        def main(basepath, filename):
            main = QApplication(sys.argv)
            u_window = window()
            u_window.createUI(basepath, filename)
            u_window.show()
            sys.exit(main.exec_())
          
            
        if __name__ == '__main__':
            print('len', len(sys.argv))
            print(sys.argv)
            if len(sys.argv) != 3:
                print("usage: python mynotes basepath filename")
            else:
                main(sys.argv[1], sys.argv[2])
        
        
        1 Reply Last reply
        0
        • H Offline
          H Offline
          hermes
          wrote on last edited by
          #4

          self.c_file contains a string of the currently displayed file.
          The files themselves are plain text files (or with QT 5.14 added markdown support) and markdown ascii text. With self.model.setNameFilters(['*.md']) I currently filter for fileextensions ".md"

          1 Reply Last reply
          0
          • H Offline
            H Offline
            hermes
            wrote on last edited by
            #5

            Dear Denni,

            I'm very sorry for not having replied earlier - I somehow did not get a notification and was moving flat in the meantime, so I forgot about this pet-project for a while.

            Any ascii file will do - if you have qt > 5.14 it could also be markdown formatted. So it could e.g. be

            this is the heading

            • this is the first line
            • this is the second line

            end.

            The files are meant to contain a kind of todo list for myself.

            1 Reply Last reply
            0
            • H Offline
              H Offline
              hermes
              wrote on last edited by
              #6

              I figures out that I was chasing something completly wrong.. In the end it was simply that I had incorrectly switched the order of two commands...
              self.loadfile(filename)
              self.c_file = filename
              ... What a basic mistake...

              1 Reply Last reply
              0

              • Login

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