Reputation: 107
I want the "Add" function to run when I input a number into "LE1" and press the "Enter" key on the keyboard. I also want the line edit to clear its text when I select it for editing.
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLineEdit, QLabel, QGridLayout, QWidget, QDialog
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.Glayout = QGridLayout(centralWidget)
self.LE1 = QLineEdit('Input Number',self)
self.LE1.keyPressEvent(self.KPE)
Label1 = QLabel('+ 1 =',self)
self.LE2 = QLineEdit(self)
self.Glayout.addWidget(self.LE1)
self.Glayout.addWidget(Label1)
self.Glayout.addWidget(self.LE2)
def Add(self):
Num = float(self.LE1.text())
math = Num + 1
ans = str(math)
self.LE2.setText(ans)
def KPE(self):
if event.key() == Qt.Key_Enter:
self.Add()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Upvotes: 1
Views: 3000
Reputation: 243897
keyPressEvent is a method that if you override it that way you are losing the default behavior, besides it is unnecessary since QLineEdit has the returnPressed signal that notifies if Enter is pressed.
On the other hand, converting a string to floating can throw an exception so you should prevent that case, another better option is to use a widget that allows only numerical values with QSpinBox or QDoubleSpinBox, or at least restrict the values that are entered into the QLineEdit with a QValidator appropriate.
And finally do not use the word math as a variable name since that is the name of a library that could cause you problems in the future.
Considering the above, the solution is:
from PyQt5.QtWidgets import (
QApplication,
QGridLayout,
QLineEdit,
QLabel,
QMainWindow,
QWidget,
)
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.LE1 = QLineEdit("Input Number")
self.LE1.returnPressed.connect(self.add)
Label1 = QLabel("+ 1 =")
self.LE2 = QLineEdit()
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
layout = QGridLayout(centralWidget)
layout.addWidget(self.LE1)
layout.addWidget(Label1)
layout.addWidget(self.LE2)
def add(self):
try:
num = float(self.LE1.text())
num += 1
self.LE2.setText(str(num))
except ValueError:
pass
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Upvotes: 1