Search code examples
qtqlineeditqtgui

QLineEdit -- how to enter single value -- with no spaces


I have made an editor in which i have to enter a Hex or decimal value in each field. Here the field i am using is QLineEdit.

Now requirement is that each Qlineedit box accept only one value without spaces. Then i can read this text value & convert it directly from string to decimal.

Is it possible to make QlineEdit to accept only one value without spaces ? Boxes in below figure are QLineEdit.

I do not want to use combo box here.

enter image description here


Solution

  • To build on Lego Stormtroopr's answer, I think QValidator is a good and simple option. For example

    dialog->lineedit1->setValidator(new QRegExpValidator( QRegExp("[0-9]{1,20}"), this ));
    

    Here, the QRegExp denotes that you shall only accept digits from 0 to 9 and no other key-presses (spaces or letters) and you shall accept atleast 1 and maximum 20 characters (digits). You then set your lineedit's validator to this value. For more information, you can visit http://qt-project.org/doc/qt-5.0/qtcore/qregexp.html

    or for a double,

    QDoubleValidator *myDblVal = new QDoubleValidator( 0.0, MAX_VALUE, 1, this);
    myDblVal->setNotation( QDoubleValidator::StandardNotation );
    dialog->lineedit1->setValidator( myDblVal );
    

    Here you simply use the inbuilt Qt functionality for double validation. You shall only accept a decimal between 0 and MAX_VALUE.