【问题标题】:How to make that Pyqt5 LineEdit accepts only numbers如何使 Pyqt5 QLineEdit 只接受数字
【发布时间】:2021-07-21 07:24:57
【问题描述】:

目前,我正在使用 python 和 PYQT5 开发一个程序,其中用户输入只能是数字。问题是我不知道该怎么做。例如当我得到这个变量时

VAR_1=float(self.ui.lineEdit.text())

我需要输入的文本只是一个数字。我的意思是当用户试图写一个字母 o 符号时,什么也没有发生。

【问题讨论】:

  • Qt 提供了QSpinBox,它已经可以满足您对整数的需求,而如果您需要浮点数,则有QDoubleSpinBox。可以实现 QLineEdit 来做同样的事情,但这通常用于非常罕见和非常特殊的情况。

标签: python pyqt


【解决方案1】:

使用/尝试 setValidatorsetInputMask 方法

import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ButtonName(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Example - Validator")
        self.setGeometry(800, 200, 200, 200)
        self.UI()
        self.layouts()
        self.show()

    def UI(self):
        self.lbl_integer = QLabel("Integer Validator")
        self.textbox_integervalidator = QLineEdit()
        self.textbox_integervalidator.setPlaceholderText("upto 3 digit value only accept")
        self.textbox_integervalidator.setValidator(QIntValidator(1, 999, self))

        self.lbl_double = QLabel("Double Validator")
        self.textbox_doublevalidator = QLineEdit()
        self.textbox_doublevalidator.setValidator(QDoubleValidator(0.99, 99.99, 2))

        self.lbl_regexp = QLabel("RexExp Validator")
        self.textbox_regexpvalidator = QLineEdit()
        reg_ex_1 = QRegExp("[0-9]+.?[0-9]{,2}") # double
        # reg_ex_2 = QRegExp("[0-9]{1,5}")  # minimum 1 integer number to maxiumu 5 integer number
        # reg_ex_3 = QRegExp("-?\\d{1,3}")  # accept negative number also
        # reg_ex_4 = QRegExp("")
        self.textbox_regexpvalidator.setValidator(QRegExpValidator(reg_ex_1))

    def layouts(self):
        mainlayout = QVBoxLayout()
        mainlayout.addWidget(self.lbl_integer)
        mainlayout.addWidget(self.textbox_integervalidator)
        mainlayout.addWidget(self.lbl_double)
        mainlayout.addWidget(self.textbox_doublevalidator)
        mainlayout.addWidget(self.lbl_regexp)
        mainlayout.addWidget(self.textbox_regexpvalidator)
        self.setLayout(mainlayout)

def main():
    app = QApplication(sys.argv)
    mainwindow = ButtonName()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

【讨论】:

  • 您提到使用setInputMask,您也愿意解释一下吗?
  • 我建议还使用valuesetValue 方法和valueChanged 信号创建子类。
  • 电话号码格式-> self.textbox_inputmask_1.setInputMask("+99-99999 99999;_") 日期格式->self.textbox_inputmask_2.setInputMask("99/99/9999;_ ") 。用于字母数字格式 -> self.textbox_inputmask_3.setInputMask(">99AAAAA9999A9A9; ") @ musicamante
【解决方案2】:

尝试为您的行编辑制作一个蒙版:

self.lineEdit.setInputMask("00")

当你在Mask中输入“0”时,代码会明白它只能是数字。放置的零数量将是 lineedit 将接受的房屋数量。在这种情况下,lineEdit 如何和“00”接受两个房子(十房子)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2011-04-17
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多