Home > Mobile >  How to generate text in a new line in text edit?
How to generate text in a new line in text edit?

Time:02-18

So I am creating a speech-to-text generator gui in pyqt5. The program takes input from microphone and sets the text of the text area accordingly but everytime the user takes an input, the whole text of the text edit changes. Is there any method as how to generate the second input in a new line in the text edit. Below is the code I am using.

This is the coding part for the text edit portion

    self.text_area = QtWidgets.QTextEdit(self.centralwidget)
    self.text_area.setGeometry(QtCore.QRect(10, 240, 621, 171))
    font = QtGui.QFont()
    font.setPointSize(10)
    self.text_area.setFont(font)
    self.text_area.setObjectName("text_area")

This is the method for recording

    def record(self):

    r = sr.Recognizer()
    try:
        with sr.Microphone() as source:

            audio = r.listen(source)
            MyText = r.recognize_google(audio)
            MyText = MyText.lower()
            self.text_area.setText(MyText)

    except Exception as e4:
        print(e4)

Please help me!

CodePudding user response:

You want to add the new text to the existing

allText=self.text_area.toPlainText() myText
self.text_area.setText(allText)

CodePudding user response:

Use the insertPlainText method to add text to the QTextEdit. Add a newline (\n) in front of the string you want to add.

It's worth noting that insertPlainText adds text to where the cursor is. Because it might not be at the end, moveCursor(QTextCursor.End) is called to move the cursor to the end.

To preserve the current position of the cursor, the cursor position is saved and restored before/after adding the text, using the textCursor and setTextCursor methods.

Change these lines:

        with sr.Microphone() as source:

            audio = r.listen(source)
            MyText = r.recognize_google(audio)
            MyText = MyText.lower()
            self.text_area.setText(MyText)

to:

        with sr.Microphone() as source:
            audio = r.listen(source)
            MyText = r.recognize_google(audio)
            MyText = MyText.lower()
            cursor = self.text_area.textCursor()
            self.text_area.moveCursor(QTextCursor.End)
            self.text_area.insertPlainText(f"\n{MyText}")
            self.text_area.setTextCursor(cursor)

Don't forget to add this import: from PyQt5.QtGui import QTextCursor

  • Related