Sunday

[Fahrenheit <=> Celsius] Temperature Converter Tutorial using Qt Designer, Qt Creator



Choose Qt Creator Menu | File |New File or Project… | Qt Widget Project | Qt Gui Application.

Widget
Property
Value
MainWindowTempConverter
windowTitle
[Fahrenheit <=> Celsius] Temperature Converter
lineEditFahrenheit
None
None
lineEditCelsius
None
None
labelFahrenheit
text
Fahrenheit value:
labelCelsius
text
Celsius value:

Right click widget | Go to slot… | “Go to slot” window pops up | Select signal: returnPressed()
Widget, Slot
Signal
Implementation
lineEditFahrenheit
returnPressed()
See code below
lineEditCelsius
returnPressed()
See code below

void MainWindow::on_lineEditFahrenheit_returnPressed()
{
    QString strFahrenheit = ui->lineEditFahrenheit->text();  //try 212F = 100C
    double fahrenheit = strFahrenheit.toDouble();
    double celsius = (fahrenheit - 32)*5.0/9;
    qDebug() << celsius << endl; //needs to "#include <QtDebug>"
    QString strCelsius;
    strCelsius.setNum(celsius, 'f', 0);
    //f format is without E/10^.
    //zero is the precision where zero number of digits after the decimal point.
    // Other valid character formats are 'e', 'E', 'f', 'g' and 'G'.
    // 'g' is after E and F, g uses either e or f format.
    ui->lineEditCelsius->setText(strCelsius);
}

void MainWindow::on_lineEditCelsius_returnPressed()
{
    QString strCelsius = ui->lineEditCelsius->text();
    double celsius = strCelsius.toDouble();
    double fahrenheit = 9/5.0*celsius + 32;
    qDebug() << fahrenheit << endl;
    QString strFahrenheit;
    strFahrenheit.setNum(fahrenheit, 'f', 0);
    ui->lineEditFahrenheit->setText(strFahrenheit);
}

Press “Ctrl+R” to compile and run Qt project.

Notes:
Press F1 for Context Help of Qt function names.
For a better Qt help, click Help Mode Selector at the LHS toolbar, then choose "Index" from drop down menu. Using this way, you can look for more information for any Qt function names.

No comments:

Measure execution time with Julia, example using sorting algorithms

# random integers between 1 and 100 inclusive, generate thousands of them x = rand ( 1 : 100 , 100000 ) @time sort (x; alg=InsertionSort, r...