使用 PyQt5 lineEdit 小部件,是否有任何简单的方法只能使用整数值?
Using PyQt5 lineEdit widget, is there any simple way only integer values are available?
我尝试构建一个代码,在 lineEdit Widget 上输入特定数字并按下 Widget 按钮,我可以获得该值作为整数类型。但我得到的值类型仍然是字符串。有没有什么漂亮的方法可以将 lineEdit Widget 中的值类型限制为整数?另外,如果lineEdit中的value类型不是整数,是否会弹出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 不为空)。
self.le.setValidator(QIntValidator())
# Accessing the text
value = int(self.le.text())
要了解更多信息,请查看 setValidator method. You might also want to consider using QSpinBox,它专为整数设计,可以 return 直接使用 QSpinBox.value()
一个整数
我尝试构建一个代码,在 lineEdit Widget 上输入特定数字并按下 Widget 按钮,我可以获得该值作为整数类型。但我得到的值类型仍然是字符串。有没有什么漂亮的方法可以将 lineEdit Widget 中的值类型限制为整数?另外,如果lineEdit中的value类型不是整数,是否会弹出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 不为空)。
self.le.setValidator(QIntValidator())
# Accessing the text
value = int(self.le.text())
要了解更多信息,请查看 setValidator method. You might also want to consider using QSpinBox,它专为整数设计,可以 return 直接使用 QSpinBox.value()