Search code examples
pythonintegerpyqt5qmessagebox

Using PyQt5 lineEdit widget, is there any simple way only integer values are available?


I try to build a code that input a certain number on lineEdit Widget and press the button Widget and I can get that value as integer type. But still the type of value I get is string. Is there any beautiful way that I can restrict type of value in lineEdit Widget as integer? Furthermore, if the type of value in lineEdit is not a integer, can Messagebox pop up showing that you input a wrong value?

import sys
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QBoxLayout
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit, QPushButton
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt
from PyQt5 import QtGui

class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        self.init_widget()

    def init_widget(self):

        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        self.le = QLineEdit()
        self.btn = QPushButton("connect")
        self.btn.clicked.connect(self.func1)

        form_lbx.addWidget(self.le)
        form_lbx.addWidget(self.btn)

    def func1(self):
        value = self.le.text()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = Form()
    form.show()
    exit(app.exec_())

Solution

  • You can use QIntValidator() to restrict input to integers only. This way you know the input will only contain digits, and you can convert the text to an int without having to worry about errors (as long as the LineEdit is not empty).

    self.le.setValidator(QIntValidator())
    
    # Accessing the text
    value = int(self.le.text())
    

    To learn more check out the setValidator method. You might also want to consider using QSpinBox, which is designed for integers and can return an int directly with QSpinBox.value()