Important: Please read the Qt Code of Conduct -

Problem with getting text from PlainTextEdit

  • Via TabWidget as central widget my little programm displays a QPainTextEdit. What i want:

    • TabWidget which displays a custom PlainTextEdit (works)

    • a save function which saves the written text e.g. as *.txt file
      This save-function should only save the text file which is 'active' in the TabWidget if multible tabs are opened.

    The problem with my code is, that for some reason the toPlainText() function does not get the written text and prints 'None' if i want to print the written text.

    from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QWidget, QMenu, QMessageBox, qApp, QTextEdit, QPlainTextEdit, QTabWidget,QVBoxLayout, QInputDialog, QFileDialog
    from PyQt5.QtGui import QIcon, QImage, QColor, QPainter, QTextFormat, QFontMetricsF
    from PyQt5.QtCore import Qt, pyqtSlot, QRect, QSize
    import sys
    from PyQt5.Qt import QAction
    from idlelib import statusbar
    import numpy as np
    class QCodeEditor(QPlainTextEdit):
       #some unnecessary code for this problem to customize the QPlainTextEdit
        def getText(self):
    class Window(QMainWindow):
        def __init__(self):
            top = 50
            left = 50
            width = 1800
            heigt = 900
            icon = "src/icons/icon.png"
            self.setGeometry(top, left, width, heigt)
            self.layout = QVBoxLayout(self)
            # Initialize tab screen
            tabs = QTabWidget()
            tab1 = QWidget()
            #self.tabs.setStyleSheet("background-color: rgb(36, 36, 36);")
            # Add tabs
            tab1.layout = QVBoxLayout(self)
            self.texteditor = QCodeEditor()
            self.texteditor.setStyleSheet("background-color: rgb(36, 36, 36); color: rgb(255, 255, 255);font-size: 15px;font-family: Bookman;")
            def newfileEvent(self, name="Untitled"):
                widget = QWidget()
                tabs.addTab(widget, name)
                widget.layout = QVBoxLayout()
                textedit = QCodeEditor()
                textedit.setStyleSheet("background-color: rgb(36, 36, 36); color: rgb(255, 255, 255);font-size: 15px;font-family: Bookman;")
            def file_save(self):
                # S_File will get the directory path and extension.
                S__File = QFileDialog.getSaveFileName(None,'SaveTextFile','/', "All Files(*.*);; Text Files (*.txt)")
                text = QCodeEditor().getText()

  • Lifetime Qt Champion


    You call print in your getText method and return nothing from it hence the result you get as returning nothing from a python method corresponds to "return None".

Log in to reply