使用正则表达式 QRegExp
单行输入框 QLineEdit
限制内容只可输入10个数字
正则表达式内容: [0-9]{1,10}
限制内容只可输入10个字母或数字
正则表达式内容: [A-Za-z0-9]{1,10}
限制内容第一个字符必须是字母
正则表达式内容:[A-Z](.){1,10} 此处第一个内容后可输入除换行符之外的所有字符,汉字也可输入,按一个单位计算
例子
实现一个只接受11个字母或数字的单行输入框,输入框内容合法就使一个Button可用
代码
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QRegExp regExp("[A-Za-z0-9]{1,11}");
//设置正则表达式,可接受字母,数字类型的数据,但不超过11个
ui->lineEdit->setValidator(new QRegExpValidator(regExp, this));
//为输入框设置验证,限制可输入的内容(正则表达式regExp
ui->okButton->setEnabled(false);
connect(ui->cancelButton, SIGNAL(clicked(bool)), this, SLOT(close()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_lineEdit_textChanged(const QString &)
{
ui->okButton->setEnabled(ui->lineEdit->hasAcceptableInput());
}