Loading

QLineEdit限定只能输入整数

QLineEdit限定输入整数时遇到的问题

问题

QValidator常常用于判断数据的合法性,QLineEdit,QSpinBox,QComboBox中经常使用该类。

QLineEdit要限制输入整数,那么添加语句lineEdit->setValidator(new QIntValidator(100, 1000, this)),理论上可以实现限定只能输入100-1000的整数,但是经过测试发现输入0依旧是可以的,这是什么原因呢?

查阅官方文档,有关QValidator的详细描述是这么说的:

fixup() is provided for validators that can repair some user errors. The default implementation does nothing. QLineEdit, for example, will call fixup() if the user presses Enter (or Return) and the content is not currently valid. This allows the fixup() function the opportunity of performing some magic to make an Invalid string Acceptable.

这段文字大致说的是使用QLineEdit,用户按下回车或是文本框中的当前内容是无效的时候,QLineEdit会调用fixup()函数去试图纠正这个错误,但是QValidator中并没有实现fixup()函数,QValidator的派生类QIntValidator也并没有实现该函数,因此该问题的方法就是通过创建一个类去继承QIntValidator。

代码

myintvalidator.h

#ifndef MYINTVALIDATOR_H
#define MYINTVALIDATOR_H
#include <QIntValidator>

class MyIntValidator : public QIntValidator
{
    Q_OBJECT
public:
    explicit MyIntValidator(QObject *parent = nullptr);

    MyIntValidator(int bottom, int top, QObject *parent);
    void setRange(int bottom, int top) override;	//设置整数的范围
    virtual State validate(QString &input, int &pos) const override;    //pos:the cursor position光标位置
    virtual void fixup(QString &input) const override;
};

#endif // MYINTVALIDATOR_H

myintvalidator.cpp

#include "myintvalidator.h"

MyIntValidator::MyIntValidator(QObject *parent)
    : QIntValidator(parent)
{
}

MyIntValidator::MyIntValidator(int bottom, int top, QObject *parent)
    : QIntValidator(bottom, top, parent)
{
}

void MyIntValidator::setRange(int bottom, int top)
{
    QIntValidator::setRange(bottom, top);
}

QValidator::State MyIntValidator::validate(QString &input, int &pos) const
{
    return QIntValidator::validate(input, pos); //调用基类的validate
}

//出现无效值或按下Enter键,QLineEdit会自动调用fixup()
void MyIntValidator::fixup(QString &input) const
{
    input = QString("%1").arg(bottom());    //出现无效值时使用下限去代替无效值
}

其中QValidator::State MyIntValidator::validate(QString &input, int &pos) const是重写基类QValidator的validate函数,返回值QValidator::State是一个枚举类型(本质上是整型常量),QValidator::Intermediate指的是中间值,举个例子,限定的范围是10-99,输入4,那么4就可能是一个中间值,还需进一步判断。
image

调用MyIntValidator类:lineEdit->setValidator(new MyIntValidator(1000, 1000000, this))

测试之后,当用户按下Enter时或是取消选中QLineEdit才会实现数据合法性的检测并使用下限值1000去代替

参考链接:

https://bbs.csdn.net/topics/350177184

https://doc.qt.io/qt-5/qvalidator.html

posted @ 2024-06-21 00:58  记录学习的Lyx  阅读(12)  评论(0编辑  收藏  举报