Displaying text in Qt
-
Hi,
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
@int num1;
int num2;
int total;cout << "First number" << endl;
cin >> num1;
cout << "Second number" << endl;
cin >> num2;//calculate
total = num1 * num2;
//display result
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 ....
@void MainWindow::on_pushButton_clicked()
{
int num1 = 5;
int num2 = 10;
int total;
total = num1 + num2;ui->textEdit->setPlainText(total);
}@
... 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:
@void MainWindow::on_pushButton_clicked()
{
QString num1 = ui->textEdit->toPlainText();
QString num2 = ui->textEdit_2->toPlainText();
int num3 = num1.toInt()+num2.toInt();
QString num4;
num4.setNum(num3);
ui->textEdit_3->setPlainText(num4);
}@
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
@ui->textEdit_3->setPlainText(QString::number(num3, 10));@
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
@void MainWindow::on_pushButton_clicked()
{
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()
ui->plainTextEdit->setPlainText(QString::number(total));@
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.