QLineEdit限定只能輸入整數

记录学习的Lyx發表於2024-06-21

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

相關文章