参考:Qt中LineEdit编辑框限制数字输入整理
运行环境:win10,VS2022,QT6.3
2022/1/12 添加槽函数版本,要获取发送者。方便复用,可多个lineedit连同一个槽函数。
ui界面布局,就放了一个qlineEdit和一个button
undoTest.h
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_undoTest.h"
class undoTest : public QMainWindow
{
Q_OBJECT
public:
undoTest(QWidget *parent = Q_NULLPTR);
// 设置lineedit输入范围
void SlotLineEditLimit();
private:
Ui::undoTestClass ui;
};
undoTest.cpp文章来源:https://www.toymoban.com/news/detail-647374.html
//#pragma execution_character_set("utf-8")
#include "undoTest.h"
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QtCore5Compat\QRegExp>
#include <QMessageBox>
#include <QObject>
#include <QValidator>
undoTest::undoTest(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//qt5方法
//QRegExp qregexp("[0-9\\.-]+$");
//QValidator* validator = new QRegExpValidator(qregexp);
//qt6方法
QRegularExpression regExp("[0-9\\.-]+$");
QRegularExpressionValidator* validator = new QRegularExpressionValidator(regExp, this);
ui.lineEdit->setValidator(validator);
connect(ui.lineEdit, &QLineEdit::editingFinished, [=](void) {
double val = ui.lineEdit->text().toDouble();
if (val<0||val>100)
{
QMessageBox box(QMessageBox::Information, QString::fromUtf8("提示"),
QString::fromUtf8("请输入1-100范围内的数字!"), QMessageBox::Ok, this);
box.exec();
ui.lineEdit->setFocus();
ui.lineEdit->setCursorPosition(ui.lineEdit->text().size());
ui.lineEdit->selectAll();
ui.lineEdit->undo();
}
});
// or
connect(ui.lineEdit, &QLineEdit::editingFinished, this, &undoTest::SlotLineEditLimit);
}
void undoTest::SlotLineEditLimit()
{
QLineEdit * this_lineedit = qobject_cast<QLineEdit*>(sender());
double val = this_lineedit->text().toDouble();
if (val < 1 || val>100)
{
QMessageBox box(QMessageBox::Information, QString::fromUtf8("提示"),
QString::fromUtf8("请输入1-100范围内的数字!"), QMessageBox::Ok, this);
box.exec();
this_lineedit->setFocus();
this_lineedit->setCursorPosition(this_lineedit->text().size());
this_lineedit->selectAll();
this_lineedit->undo();
}
}
main.cpp文章来源地址https://www.toymoban.com/news/detail-647374.html
#include "undoTest.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
undoTest w;
w.show();
return a.exec();
}
到了这里,关于Qt|QLineEdit输入限制以及给出提示并复原值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!