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