如何使pyqt5 lineedit只接受数字

3wabscal  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(1315)

目前,我正在用python和pyqt5编写一个程序,其中用户输入只能是数字。问题是我不知道怎么做。例如当我得到这个变量 VAR_1=float(self.ui.lineEdit.text()) 我需要输入的文本只是一个数字。我的意思是,当用户试图写一个字母o符号时,什么也没有发生。

luaexgnf

luaexgnf1#

使用/尝试setvalidator或setinputmask方法

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.show()
        self.UI()
        self.layouts()

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

相关问题