Regex validator
So far, other answers provide solutions only for a relatively limited number of numbers. However, if you are interested in an arbitrary or variable number of digits, you can use the QRegExpValidator , passing a regular expression that accepts only digits (as noted in user2962533's comment). Here is a minimal, complete example:
#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 has its advantages (and this is only an understatement). It allows many other useful checks:
QRegExp("[1-9][0-9]*") // leading digit must be 1 to 9 (prevents leading zeroes). QRegExp("\\d*") // allows matching for unicode digits (eg 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 (eg 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 (eg 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. // NB invalid addresses can still be entered: "999.999.999.999".
Learn more about online editing behavior.
According to the documentation :
Please note that if a validator is installed in the edit line, the returnPressed () / editFinished () signals will only be sent if the validator returns QValidator :: Acceptable.
Thus, editing the line will allow the user to enter numbers, even if the minimum amount has not yet been reached. For example, even if the user did not enter text against the regular expression "[0-9]{3,}" (which requires at least 3 digits), editing the line still allows the user to enter input to achieve this minimum requirement. However, if the user finishes editing, not satisfying the requirement of "at least 3 digits", the input will be incorrect; the returnPressed() and editingFinished() signals will not be emitted.
If the regular expression has a maximum boundary (for example, "[0-1]{,4}" ), then editing the line will stop any input after 4 characters. In addition, for character sets (ie, [0-9] , [0-1] , [0-9A-F] , etc.) Line editing allows you to enter only characters from this particular set.
Note that I only tested this with Qt 5.11 on macOS, and not on other versions of Qt or operating systems. But given the cross-platform Qt scheme ...
Demo: Regex Validators Showcase