How to show all entered text in line edit to text

2019-08-22 05:05发布

问题:

Below is my code. I want to show all entered text in line edit to textedit widget. Whenever i entered a text in line edit the same will show in textedit widget. But it's overwrite with latest one. but i want previous user entered text also in text edit widget.

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        self.title = QtGui.QLabel("TO DO APP")
        self.title.setStyleSheet("font: bold 30ft AGENTORANGE")
        self.title.setAlignment(QtCore.Qt.AlignCenter)
        # self.title.move(200,10)
        self.title.resize(90,50)


        self.message_box = QtGui.QLineEdit()
        self.btn = QtGui.QPushButton("add")

        self.btn.clicked.connect(self.message_Chat)

        self.tedit = QtGui.QTextEdit()

        self.hbox = QtGui.QHBoxLayout()
        self.hbox.addWidget(self.message_box)
        self.hbox.addWidget(self.btn)
        # self.btn.move(120,100)
        # self.message_box.move(220,100)

        self.vbox = QtGui.QVBoxLayout()
        self.vbox.addWidget(self.title)
        self.vbox.addLayout(self.hbox)
        self.vbox.addWidget(self.tedit) 

        self.setLayout(self.vbox)

        self.setWindowTitle("To do app")
        self.setGeometry(100,100,500,500)
        self.show()

    def message_Chat(self):
        # print(self.message_box.text()) 
        #print(self.message_box.text())
        text = self.message_box.text()
        self.tedit.setText(text)
        # cursor = self.tedit.textCursor()
        # cursor.movePosition(QtGui.QTextCursor.End)
        # self.tedit.setTextCursor(cursor)
        self.message_box.setText("")

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

回答1:

You have to use the append() method to add the text to the end, on the other hand it is more readable to use clear() to clean the QLineEdit that setText("").

def message_Chat(self):
    text = self.message_box.text()
    self.tedit.append(text)
    self.message_box.clear()