Python 使用PyQt5 lineEdit小部件,是否有任何简单的方法只提供整数值?

Python 使用PyQt5 lineEdit小部件,是否有任何简单的方法只提供整数值?,python,integer,pyqt5,qmessagebox,Python,Integer,Pyqt5,Qmessagebox,我尝试构建一个代码,在lineEdit小部件上输入一个特定的数字,然后按下按钮小部件,我可以得到整数类型的值。但我得到的值类型仍然是字符串。有什么好办法可以限制lineEdit小部件中的值类型为整数吗?此外,如果lineEdit中的值类型不是整数,是否会弹出Messagebox显示您输入了错误的值 import sys from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QBoxLayout from PyQt5.QtW

我尝试构建一个代码,在lineEdit小部件上输入一个特定的数字,然后按下按钮小部件,我可以得到整数类型的值。但我得到的值类型仍然是字符串。有什么好办法可以限制lineEdit小部件中的值类型为整数吗?此外,如果lineEdit中的值类型不是整数,是否会弹出Messagebox显示您输入了错误的值

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_())

您可以使用
QIntValidator()
将输入仅限于整数。这样您就知道输入将只包含数字,并且您可以将文本转换为int,而不必担心错误(只要LineEdit不是空的)


要了解更多信息,请查看该方法。您可能还需要考虑使用它,它是为整数设计的,并且可以直接返回一个int,它是用<代码> QSPINBOX.Valuy()/<代码> < /P>谢谢。根据您的意见,我找到了解决方案:D实际上在我的python开发环境中,我找不到您评论的QIntValidator方法。我可以使用QtGui.QIntValidator()方法找到解决方案,而不是使用上述代码。
self.le.setValidator(QIntValidator())

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