我有一个QLineEdit
,用户只能输入数字。
那么,QLineEdit
有一个只允许输入数字的设置吗?
QLineEdit::setValidator()
,例如:
myLineEdit->setValidator( new QIntValidator(0, 100, this) );
或者myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );
3.14e-7
)输入,则以下是一个快速解决方案。QDoubleSpinBox
不接受科学计数法表示的数字(Qt 5.5)。 - Frederik Aalund最好的选择是QSpinBox
。
如果需要使用双精度值,请使用QDoubleSpinBox
。
QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
正则表达式验证器
到目前为止,其他答案仅针对相对有限数量的数字提供解决方案。然而,如果你关注一个任意或可变数量的数字,你可以使用一个QRegExpValidator
,传递一个只接受数字的正则表达式(如 user2962533的评论所示)。这是一个极简、完整的例子:
#include <QApplication>
#include <QLineEdit>
#include <QRegExpValidator>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLineEdit le;
le.setValidator(new QRegExpValidator(QRegExp("[0-9]*"), &le));
le.show();
return app.exec();
}
QRegExpValidator
有其优点(这只是一种低调的说法)。它允许进行其他有用的验证:
QRegExp("[1-9][0-9]*") // leading digit must be 1 to 9 (prevents leading zeroes).
QRegExp("\\d*") // allows matching for unicode digits (e.g. for
// Arabic-Indic numerals such as ٤٥٦).
QRegExp("[0-9]+") // input must have at least 1 digit.
QRegExp("[0-9]{8,32}") // input must be between 8 to 32 digits (e.g. for some basic
// password/special-code checks).
QRegExp("[0-1]{,4}") // matches at most four 0s and 1s.
QRegExp("0x[0-9a-fA-F]") // matches a hexadecimal number with one hex digit.
QRegExp("[0-9]{13}") // matches exactly 13 digits (e.g. perhaps for ISBN?).
QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")
// matches a format similar to an ip address.
// N.B. invalid addresses can still be entered: "999.999.999.999".
更多关于行编辑行为的内容
根据文档:
请注意,如果在行编辑器上设置了验证程序,则仅当验证程序返回QValidator::Acceptable时,returnPressed()/editingFinished()信号才会发出。
因此,即使尚未达到最小数量,行编辑器也将允许用户输入数字。例如,即使用户没有针对正则表达式"[0-9]{3,}"
(需要至少3个数字)输入任何文本,该行编辑器仍允许用户键入输入以达到达到最小要求。但是,如果用户完成编辑而不满足“至少3个数字”的要求,则输入将是无效的;信号returnPressed()
和editingFinished()
将不会被发出。
如果正则表达式具有最大限制(例如"[0-1]{,4}"
),则行编辑器将停止超过4个字符的任何输入。此外,对于字符集(即[0-9]
,[0-1]
,[0-9A-F]
等),行编辑器仅允许输入该特定集合中的字符。
请注意,我仅在macOS上使用Qt 5.11进行了测试,而不是在其他Qt版本或操作系统上。但鉴于Qt的跨平台架构...
演示: 正则表达式验证器展示
QSpinBox
来实现这个目的呢?你可以使用以下代码将上/下按钮设置为不可见:// ...
QSpinBox* spinBox = new QSpinBox( this );
spinBox->setButtonSymbols( QAbstractSpinBox::NoButtons ); // After this it looks just like a QLineEdit.
//...
#include <QIntValidator>
ui->myLineEditName->setValidator( new QIntValidator);
我建议你将那行代码放在ui->setupUi(this);之后。
希望这能有所帮助。
new QIntValidator(this)
,否则当你的窗口小部件超出范围时,验证器对象将会泄漏。请注意不要改变原意,并使翻译通俗易懂。 - Alexandros