Qt中验证器的使用

Qt提速了三个内置验证器类:QdoubleValidator, QIntValidator, QRegExpValidator类

QDoubleValidator类:对于浮点数,使用QDoubleValidator时,只能限制输入的小数位数,但是无法限定数值的范围,要想限制浮点数的取值范围可以考虑采用,QRegExpValidator类

QRegExp rx("^(-?[0]|-?[1-9][0-9]{0,5})(?:\\.\\d{1,4})?$|(^\\t?$)");
QRegExpValidator *pReg = new QRegExpValidator(rx, this);
lineEdit->setValidator(pReg);

QInValidator类:提供了一个确保一个字符串包含一个在一定有效范围内的整数的验证器。
Example of use:

QLine *lineEdit;
QIntValidator* validator = new QIntValidator(0, 100, this);
lineEdit->setValidator(validator)

//上述代码说明lineEdit只能输入0—100之间的数字。
QRegExpValidator类:提供了对满足正则表达的字符串的范围检查
Example of use:

QLineEdit* lineEdit;
QReExp regExp("[A-Za-z][1-9][0-9]{0,2}");
QRegExpValidator* validator = new QRegExpValidator(regExp, this);
lineEdit->setValidator(validator);

//意思是:允许一个大写或者小写的子目,后面跟着一个范围为1-9的数字,后面再跟0个、1个或2个0—9的数字。

测试demo:

gotocelldialog.h

#ifndef GOTOCELLDIALOG_H
#define GOTOCELLDIALOG_H

#include <QDialog>

#include "ui_gotocelldialog.h"

class GoToCellDialog : public QDialog, public Ui::GoToCellDialog
{
    Q_OBJECT

public:
    GoToCellDialog(QWidget *parent = 0);

private slots:
    void on_lineEdit_textChanged();
};

#endif

gotocelldialog.cpp

#include <QtGui>

#include "gotocelldialog.h"
#include <QPushButton>

GoToCellDialog::GoToCellDialog(QWidget *parent)
    : QDialog(parent)
{
    setupUi(this);
    buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);

//    QRegExp regExp("[A-Za-z][1-9][0-9]{0,2}");
//    lineEdit->setValidator(new QRegExpValidator(regExp, this));


    QDoubleValidator* validtor = new QDoubleValidator(0,100,6, this);
    lineEdit->setValidator(validtor);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}

void GoToCellDialog::on_lineEdit_textChanged()
{
    buttonBox->button(QDialogButtonBox::Ok)->setEnabled(
            lineEdit->hasAcceptableInput());
}

main.cpp

#include <QApplication>

#include "gotocelldialog.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    GoToCellDialog *dialog = new GoToCellDialog;
    dialog->show();
    return app.exec();
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值