QLineEdit as monetary field
-
Hi, I'm trying to create a monetary field using QLineEdit.
My Qt SDK is 4.7.4 and I can't update it because it's a very big project.What I did was to create an slot which is called after the textEdited signal.
Here's the implementation:
@void MainWindow::slot_formatValue(QString text)
{
text.remove(QRegExp("[^0-9]"));
const QString new_text = brazilian.toString(text.toLongLong() * 0.01, 'f', 2);const qint32 cursor_pos = ui->lineEdit->cursorPosition(); ui->lineEdit->setText(new_text); ui->lineEdit->setCursorPosition(cursor_pos);
}@
The brazilian monetary format is ###.###,## and I want to format the text in real time.
But I'm having two problems (so far) with this code.First, when QLocale adds extra characters, the cursor moves one or two positions.
Second, because I'm getting the cursor position after the key is pressed, the cursor is moving for non-numeric values.
What could I do to fix this?
Thanks in advance.
-
Hi
First of all, you are able to place a Validator on a QLineEdit, so no need to use the QRegExp in the slot. This voids the changes of strange inputs and helps you protect your code. Make the QRegExp able to place all numeric values, one ',' character and as many '.' as people want.bq. The brazilian monetary format is ###.###,## and I want to format the text in real time.
What do you mean with this? You want to change the value while you type it?
Maybe change what signal is used from the lineEdit. You might want to use the editingFinished() signal instead. Then the user is done with editing. That is more logic than to change it as you type. This in combination with the validator should do the trick -
Jeroentje@home, thanks for the answer.
I guess I didn't explaing myself very well.
What I wanted was the user to be only able to type in digits. Letters, dots, commas, etc. would all be ignored. At the same time, the text would be formatted as the user typed, so the dots and the comma would be inserted automatically. That's why I didn't use the QValidator and the editingFinished() signal.Is there any easy way to do this? I mean, the only solution I found needed a few more lines of code, maybe more than a few.
-
Hi,
Why not use a QSpinBox with a suffix ?
-
Hi SGaist, thanks for the reply.
Is it possible to hide the up and down right arrows in the QSpinBox?
The user needs to fill the fields very quickly and manually, so those arrows would not make sense, and may even be an annoyance. -
I've not used this myself yet but you can try with:
@m_spinBox->setButtonSymbols(QAbstractSpinBox::NoButtons);@
-
Yes, that did it, the buttons were hidden.
I'll give the QSpinBox a try and post back the results.Many thanks!