Search code examples
pythonpyqt5qlineedit

How to change the content of QPyLineEdit when the program is running?


I'm writing a calculator using PyQt5, the user interface has been finished, but there is a question when I what change the content of QLineEdit. The detail way to change it is call QLineEdit.setText() method when the user pressing a button.

But when I pressing a PushButton, the program finished and shown the message like this:"Process finished with exit code 1". There are not any errors or warning informations. This is the complete program below:

# -*- coding:utf-8 -*-
import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout,
        QPushButton, QLineEdit, QVBoxLayout, QApplication, QMessageBox)


class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # grid = QGridLayout()
        qvbox = QVBoxLayout()
        gridBar = QGridLayout()
        gridWidget = QWidget()

        numberEdit = QLineEdit()
        numberEdit.setReadOnly(True)

        names = ["Cls", "Bck", "", "Close",
                 "7", "8", "9", "/",
                 "4", "5", "6", "*",
                 "1", "2", "3", "-",
                 "0", ".", "=", "+"]

        position = [(i, j) for i in range(5) for j in range(4)]

        for position, name in zip(position, names):
            if name == "":
                continue
            button = QPushButton(name)
            gridBar.addWidget(button, *position)
            button.clicked.connect(self.buttonClicked)
        qvbox.addWidget(numberEdit)
        gridWidget.setLayout(gridBar)
        qvbox.addWidget(gridWidget)

        self.setLayout(qvbox)

        self.move(300, 150)
        self.setWindowTitle("Calculator")
        self.show()

    def buttonClicked(self):
        sender = self.sender()
        self.dealData(sender.text())

    def dealData(self, data):
        self.numberEdit.setText(data) # Here, the program exited!!!
        print(data) # The output in consle was right.

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = Calculator()
    sys.exit(app.exec_())

Where have I made a mistake?


Solution

  • You must set an attribute for numberEdit so you can access it later:

    class Calculator(QWidget):
        ...    
        def initUI(self):
            ...
            self.numberEdit = QLineEdit()
            self.numberEdit.setReadOnly(True)
    

    Also, you need to append the new text, so dealData should look like this:

        def dealData(self, data):
            self.numberEdit.end(False)
            self.numberEdit.insert(data)
            print(data) # The output in consle was right.