Displaying text in Qt
I have been playing around with Qt and Qt Creator but I'm having a hard time to figuring out something incredibly easy, what I need to do is basically get two inputs (numbers) from the user, do some calculations and then display the result in a third text field when a button is clicked.
This is the C++ code
cout << "First number" << endl;
cin >> num1;
cout << "Second number" << endl;
cin >> num2;
total = num1 * num2;
cout << total << endl;@
Can someone help me to create what I have described in the above code?
I know, I know its something very simple but I cannot make it work using textEdits and plainTextEdits.
I tried ....
int num1 = 5;
int num2 = 10;
total = num1 + num2;
... but nothing.
Thanks a lot for your help!
You need to convert to QString before putting it into the textEdit.
You can try this code:
QString num1 = ui->textEdit->toPlainText();
QString num2 = ui->textEdit_2->toPlainText();
int num3 = num1.toInt()+num2.toInt();
But if you are interested in numbers, then use double spin box or spin boxes which are simpler.
Maybe a bit more readable would be to use the number function in QString and have the num1 and num2 as regular int to work with
The QString::number will convert the number into a 10base value. If a hex value needs to be displayed, use QString::number(num3, 16);
You guys are awesome!
This is my final code, I changed it to lineEdits for the inputs and to plainTextEdit to display the result. Thanks a lot for your help
QString num1 = ui->lineEdit->text();
QString num2 = ui->lineEdit_2->text();
int total = num1.toInt()+ num2.toInt(); ui->plainTextEdit->setPlainText(QString::number(total, 10));
Oke, to be really great and almost as short as possible:
@int total = ui->lineEdit->text().toInt() + ui->lineEdit_2->text().toInt()
You are able to leave the 10 out of number because when not entered it is converted for the 10 base value as default.
Thanks a lot for the improved code, that helps me to learn more.
I appreciate it.