Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

python - Add more than one line to a QTextEdit 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()) + "
")

and the important one

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

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()) + "
")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...