Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

If the answer was just decimal, I'd suggest you use a QSpinBox instead. I did find a thread on how to implement a Hexidecimal SpinBox, but unfortunately the link to the third-party widget is dead. However it does say you could:

subclass QSpinBox and reimplement textFromValue() and valueFromText() to show hexadecimal values.

With the right Decimal-to-Hexidecimal function (you don't mention what language you are using) this would be a suitable solution.

The other alternative, is to use the QLineEdit.setValidator function with a custom subclass of QValidator to provide a validation method. For this, just re-implement the QValidator.validate function to check what a "valid" value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top