简体   繁体   中英

Text from QLineEdit not displaying

I am grabbing the user input from the line edit and displaying it on the QMessageBox but it won't show for some reason. I thought maybe I wasn't grabbing the input from QLineEdit at all but when I tried printing it on the terminal (it still wouldn't show there btw) the terminal scrolled down, recognizing that there is new data in it but just not displaying it. Get what I am saying?

import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *


def main():
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())


class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        # create objects
        label = QLabel(self.tr("enter the data "))
        self.le = QLineEdit()
        self.te = QTextEdit()

        # layout
        layout = QVBoxLayout(self)
        layout.addWidget(label)
        layout.addWidget(self.le)
        layout.addWidget(self.te)
        self.setLayout(layout)

        # create connection
        self.mytext = str(self.le.text())
        self.connect(self.le, SIGNAL("returnPressed(void)"),
                     self.display)

    def display(self):
        QApplication.instance().processEvents()
        msg = QMessageBox.about(self, 'msg', '%s' % self.mytext)
        print(self.mytext)
        self.te.append(self.mytext)
        self.le.setText("")

if __name__ == "__main__":
    main() 

You are currently reading the QLineEdit in the constructor, and at that moment the QLineEdit is empty, you must do it in the slot:

def display(self):
    mytext = self.le.text()
    msg = QMessageBox.about(self, 'msg', '%s' % mytext)
    self.te.append(mytext)
    self.le.clear()

Note: use clear() to clean the QLineEdit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM