QDoubleValidator is not working? - c++

I'm trying to apply validator in a line edit box in Qt 4.2 and it is not working:
QDoubleValidator *haha= new QDoubleValidator(this);
haha->setBottom(0.00);
haha->setDecimals(2);
haha->setTop(100.00);
get_line_edit()->setValidator(haha);
or
QDoubleValidator *haha= new QDoubleValidator(0.00,100.00,2,this);
Neither way, I can still enter what ever value I want.
But if I switch to QIntValidator, it works!
So I went onto Google and did a bit search, and many people used to having the same issue. Is it a bug? or there should be some other set up I should do?

Just tripped over this one. Try setting the QDoubleValidator notation to:
doubleValidator->setNotation(QDoubleValidator::StandardNotation);

The validator documentation says that it returns "Intermediate" from "validate" when the input is an arbitrary double but out of range.
You need to distinguish intermediate input and the final input the user wants to submit by use of a line edit control (e.g. by emitting the "returnPressed" signal). If the user typed "10000" that is still a valid intermediate input for a number between 0 and 100 because the user can prefix this input with "0.".

You have to set notation to your validator
QLineEdit *firstX;
QDoubleValidator* validFirstX = new QDoubleValidator(-1000, 1000, 3, ui.firstX);
validFirstX->setNotation(QDoubleValidator::StandardNotation);
then it works but not fully correct. Interesting part is that it controls the digit numbers not number itself. For example, In this example, you can enter to QLineEdit 1000 either 9999.

&& ( input.toDouble() > top() || input.toDouble() < bottom())

This example works fine in 4.8. It doesn't look like its changed since 4.2 so I suspect the problem lies in how you are creating your QLineEdit. This is the relevent code from that example.
QLineEdit* validatorLineEdit;
validatorLineEdit = new QLineEdit;
validatorLineEdit->setValidator( new QDoubleValidator(-999.0, 999.0, 2, validatorLineEdit));
How have you created your line edit?

To clarify, use QDoubleValidator::setNotation(QDoubleValidator::StandardNotation)
Example:
QDoubleValidator* doubleValidator = new QDoubleValidator(-999.0, 999.0, 2, validatorLineEdit);
doubleValidator->setNotation(QDoubleValidator::StandardNotation);
validatorLineEdit->setValidator(doubleValidator);

If you set a validator to a QLineEdit then you can use the function hasAcceptableInput() to check whether inputed value is valid or invalid. For example:
if (!ui->lineEdit_planned_count_vrt->hasAcceptableInput())
{
slot_show_notification_message("EDIT_PLAN_COUNT_VRT", notification_types::ERROR, INVALID_INPUTED_VALUE);
return;
}
bool isOk = false;
double value = ui->lineEdit_planned_count_vrt->text().toDouble(&isOk);
//do something with the value here....

Related

Why does my QIntValidator allow inputs not in my specified range?

I am trying to set up a QIntValidator to validate input on a QLineEdit. This is what I did:
userInput = new QLineEdit("1");
userInput->setValidator(new QIntValidator ( 1, 20, this ) );
This appears to work: it does not allow any letters in. However, I can type in 0, which is out of range, and I can also type in numbers like 21, 39 and 80, all out of range of 1-20. Basically, I expect that the QIntValidator will only allow number inputs in the range 1-20, but, instead, I find that it allows all nonnegative number inputs less than 100 (I can also do 00000.)
Why is the QIntValidator not working as I expected it to and how do I fix it?
The 0 is accepted as QValidator::Intermediate state, because the user may intend to type e.g. 05, which would be valid. You won't be able to actually input the undesired value. After you press Return or move focus from the widget, having 0 in the input field, the value should return to the original (well, at least spinboxes behave so, not sure about QLineEdit).

using one Qcombobox to set value to several labels, C++

im trying to set the value from a combobox to multiple Qlabels, the idea is to populate the QcomboBox with all the values, then according to the number, (ejem 15.6) the corresponding label should change the problem is, theres too many of them to simply use a switch of something similar, but all the names of the labels are similar, HumSec_val156 corresponds to 15.6 the main idea was to use
Silo* silo = new Silo;
QString number = widget.QComboBox->currentText();
QString nameOfLabel = "HumSec_val";
nameOfLabel.append(QString::number(number));
silo->findchild<QLabel*>(nameOfLabel)->setText(valuefromCombobox);
but everytime it simply return an empty string, i did try using somthing simplier like
widget.nameOfLabel->setText(valuefromComboBox);
but nameOfLabel its just a qstring so i can mix it with the code generated from designer. Any idea what can i do? do i need to create something like a scoped enum or similar?
below i add a picture of what im doing
If I would do something like this, I would probably create a QHash<QString, QLabel*> and use that as a cache to find the matching QLabel for each name.
Declaration:
QHash<QString, QLabel*> m_hash
Storing value:
m_hash[labelName] = labelPtr;
Reading value:
QLabel* labelPtr = m_hash.value(labelName, nullptr);
if (labelPtr)
{
// Access label
}
When you remove a label remember to remove it from the hash as well:
const QString key = m_hash.key(labelPtr);
m_hash.remove(key);

How to use QlineEdit to enter integer values

I am trying to use QlineEdit.
How would I enter a value into the edit bar when I run the program and get that valued stored as a variable to be used later. So far I have only found out how to enter text using
void parameter_settings::on_lineEdit_textEdited(const QString &arg1)
{
ui->lineEdit->setText("");
}
I have a GUI that requires the user to enter a value within a specific range. That value would be stored as a variable for later use. I have read about validators but can't get it to work as intended.
I am not entirely sure what your question is, but you can get the input from a QLineEdit with the command text():
QString input = ui->lineEdit->text();
and an integer input by using:
int integer_value = ui->lineEdit->text().toInt();
As you mentioned validators: You can use validators to allow the user to insert only integers into the QLineEdit in the first place. There are different ones but I generally like to use 'RegEx' validators. In this case:
QRegExpValidator* rxv = new QRegExpValidator(QRegExp("\\d*"), this); // only pos
QRegExpValidator* rxv = new QRegExpValidator(QRegExp("[+-]?\\d*"), this); // pos and neg
ui->lineEdit->setValidator(rxv);
Note: As mentioned in the comments by Pratham, if you only require integers to be entered you should probably use a QSpinBox which does all this out-of-the-box and comes with extra handles to easily increase and decrease of the value.
Use this method:
QString str = QString::number(4.4);
ui->lineEdit->setText(str);

Line Edit setText function Qt

I have a LineEdit which I want it to present a float value. I want the float value to have 2 digits precision so I used number function like this:
float tax = value * 0.23;
Qstring strTax = QString::number(tax, 'f', 2);
qDebug() << strTax;
ui->leTax->setText(strTax);
The thing is that while in console the value is printed with 2 digits precision, the widget prints all the decimal digits which might be 3 or more (depends on the value). Is there a way to fix it? I am using Qt 5.0.
So this is the accepted answer. I finally solved my problem. The onTextUpdate had to update two more LineEdits one containing the Tax and one containing The total amount. But the one containing the totalAmount also emitted the onTextChanged to update the net value and the Tax LineEdits, without rounding the values(I Was careless!!). So I corrected the totalAmount's onTextChanged. I also updated it to check if it has focus so to know if it is its turn to update the other LineEdits or not :). The point was that someone could edit the netValue line edit and that would update the tax and total amount or someone would enter the totalAmount and that automatically would update the net Amount and tax field. Everything working now. Thank you all for answering!!
I do not have a float-version for QString::number(), so maybe try cast-to-double
ui->leTax->setText(QString::number((double)tax, 'f', 2));
But since qDebug() is already showing the correct value, you probably change your strTax somewhere else in the code.
setValidator might be your solution. Click here and here
void QLineEdit::setValidator ( const QValidator * v )
Sets this line edit to only accept input that the validator, v, will accept. This allows you to place any arbitrary constraints on the text which may be entered.
Also, Set the number of decimal places with setDecimals().
So, it should looks like this :
// bottom (-999.0), top (999.0), decimals (2)
lineEdit->setValidator(new QDoubleValidator(-999.0, 999.0, 2, lineEdit));

Qt QInputDialog parameter list

I am starting a Qt course this semester. Having looked at the official documentation as well as some on line examples I am confused by the parameter lists of the QInputDialog and QMessagebox classes.
Is there anywhere where one could find some decent info as to what to pass when creating the class / form?
Right now I have this by trial error
tempC = QInputDialog::getDouble(0, "Temperature Converter",
"Enter the temperature in Celsius to convert to Fahrenheit:", 1);
Looking at the official docs doesn't help a lot either (at least not for me yet) as it says this:
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
tr("Amount:"), 37.56, -10000, 10000, 2, &ok);
as an example.
Any links will be much appreciated.
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
tr("Amount:"), 37.56, -10000, 10000, 2, &ok);
A dialog will popup with parent the widget in which you are using this function. (this)
The dialog's title will be QInputDialog::getDouble() (tr is used in order to translate this string if you want using QtLinguist)
Inside the dialog will be a double spibox and a label
The label's string will be Amount:
The default value of the spinbox (what you see when the dialog popups) will be 37.56
The minimum value will be -10000 (you will not be able to set a value less than this)
The maximum value will be 10000 (you will not be able to set a value greater than this)
Two decimal point will be displayed, eg 3.478 will be displayed as 3.48.
If the user presses the Ok button then the ok argument will be set to true, otherwise it will be set to false
Check the documentation which includes an example for more details.