Format text in QLineEdit

  • I'm trying to build a custom QLineEdit control for inputting and displaying values with units. For example, an editor for distances allows the user to input in meters, feet, kilometers, etc. I want the display to include the units string at the end. I also want to control the formatting of the number (digits after decimal, commas, etc.).

    I think what I need is to figure out when the user is finished editing (leave focus, enter key), then validate the input, then format the result for display. I have written the validator, so I think I need to connect the editingFinished() signal to something -- but how to set theQLineEdit text without causing an infinite loop?


  • A proper "input mask": - like <code>"#nnnn.nn meters"</code> doesn't serve your purpose?

    If you set the validator - which can be freely combined with an input mask - using QLineEdit::setValidator() the line edit only accepts text satisfying the validator and the editingFinished() signal is emitted only if the text satisfies the validator as well. You do not need to manually validate anything.

    You do not need to connect to the signal either if you don't want to. QLineEdit::hasAcceptableInput() returns true if the current text satisfies the input mask and the validator.

  • Sorry I wasn't clear.

    I don't want to constrain how the user enters the value, which is my understanding of input mask functionality. I want the user to be able to enter a number any way he wants, then when he's finished, display the number with appropriate formatting and appended units. For example, user enters:


    Component displays, for example:

    123,456.79 km

    ... if the component units are set to kilometers, commas is true, and formatting is set for fixed notation with 2 decimals.

    Or, user enters:


    Component displays

    1.23e18 km

    I think I see how to take user input, check it for validity (using a validator as you suggested), and I know how to format the number, but I don't see how to set the string the QLineEdit will display without triggering additional validation, or losing undo?

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.