在QTextEdit中添加多行PyQt
我在使用PyQT的QTextEdit时遇到了一个挺奇怪的问题。
当我从QLineEdit输入一个字符串时,它会被添加进去,但如果我再输入一个新的字符串,第一个字符串就消失了。我想这可能是因为我没有把文本追加上去。
有没有人知道我该怎么做才能解决这个问题呢?
以下是相关的代码:
self.mytext.setText(str(self.user) + ": " + str(self.line.text()) + "\n")
还有一个很重要的部分
self.mySignal.emit(self.decrypt_my_message(str(msg)).strip() + "\n")
补充
我搞明白了,我需要使用一个 QTextCursor
。
self.cursor = QTextCursor(self.mytext.document())
self.cursor.insertText(str(self.user) + ": " + str(self.line.text()) + "\n")
1 个回答
20
setText()
方法会把当前的所有文本都替换掉,所以你只需要使用 append()
方法就可以了。(注意,这两个方法都会自动在文本后面加一个换行符。)
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_())