Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add more than one line to a QTextEdit PyQt

Tags:

python

pyqt

I am experiencing a rather strange issue with my PyQT QTextEdit.

When I enter a string from my QLineEdit it adds it but say I enter another the first string disappears I assume that's because I am not appending the text.

Any idea how I can do this?

Here is the relevant code:

self.mytext.setText(str(self.user) + ": " + str(self.line.text()) + "\n")

and the important one

self.mySignal.emit(self.decrypt_my_message(str(msg)).strip() + "\n")

Edit

I figured it out I needed to use a QTextCursor

self.cursor = QTextCursor(self.mytext.document())
self.cursor.insertText(str(self.user) + ": " + str(self.line.text()) + "\n")
like image 467
ADE Avatar asked Oct 14 '11 17:10

ADE


1 Answers

The setText() method replaces all the current text, so you just need to use the append() method instead. (Note that both these methods automatically add a trailing newline).

import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.button = QtGui.QPushButton('Test')
        self.edit = QtGui.QTextEdit()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self.button.clicked.connect(self.handleTest)

    def handleTest(self):
        self.edit.append('spam: spam spam spam spam')

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())
like image 94
ekhumoro Avatar answered Sep 21 '22 22:09

ekhumoro