使用正则表达式限制QLineEdit
的测试例子:
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public Q_SLOTS:
void accept() override;
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QMessageBox>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
ui->lineEdit_1->setValidator(new QRegExpValidator(QRegExp(tr("[0-9]+")),this)); //设置只能输入数字
ui->lineEdit_2->setValidator(new QRegExpValidator(QRegExp(tr("[-]?[0-9]+,[0-9]+")),this)); //设置
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::accept()
{
if(!QRegExp(tr("[0-9]+")).exactMatch(ui->lineEdit_1->text()))
{
QMessageBox temMB(QMessageBox::Warning,
tr("警告"),
tr("第一行输入错误,默认输入是1\n请问是否设置为默认值?"),
QMessageBox::Yes | QMessageBox::No);
temMB.setButtonText(QMessageBox::Yes,tr("是"));
temMB.setButtonText(QMessageBox::No,tr("否"));
if(temMB.exec() == QMessageBox::Yes)
ui->lineEdit_1->setText(tr("1"));
return;
}
if(!QRegExp(tr("[-]?[0-9]+,[0-9]+")).exactMatch(ui->lineEdit_2->text()))
{
QMessageBox temMB(QMessageBox::Warning,
tr("警告"),
tr("第二行输入错误,默认输入是1,1\n请问是否设置为默认值?"),
QMessageBox::Yes | QMessageBox::No);
temMB.setButtonText(QMessageBox::Yes,tr("是"));
temMB.setButtonText(QMessageBox::No,tr("否"));
if(temMB.exec() == QMessageBox::Yes)
ui->lineEdit_2->setText(tr("1,1"));
return;
}
qDebug()<<ui->lineEdit_1->text()<<'\n'<<ui->lineEdit_2->text();
QDialog::accept();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
注意,我发现虽然设置了正真表达式后,QLineEdit
只能保证输入的时候可以按照其规则输入,但是不能保证客户使用的时候输入完全,比如需要输入坐标(23,34),客户可能没有输入逗号,还是可以按确定按钮的,为了让其完全有保证,必须在按下接受按钮的时候再次检验,这是可以重写QDialog
的accept()
函数,并在里面再次使用正则表达式QRegExp
类的exactMatch
进行匹配来达到目的。