How to do it…

Make yourself a currency converter with these simple steps:

  1. Open Qt Creator and create a new Qt Widgets Application project from File | New File or Project.
  2. Open the project file (.pro) and add the network module to our project:
QT += core gui network
  1. Open mainwindow.ui and remove the menu bar, toolbar, and status bar from the UI.
  2. Add three horizontal layouts, a horizontal line, and a push button to the canvas. Left-click on the canvas and continue by clicking the Lay Out Vertically button on top of the canvas. Set the label of the push button to Convert. The UI should look something like this:

  1. Add two labels to the top layout and set the text of the left one to From:, followed by the right one to To:. Add two Line Edit widgets to the second layout and set both their default values to 1:

  1. Select the line edit on the right and enable the readOnly checkbox located in the Property pane:

  1. Set the cursor property to Forbidden so that users know it's not editable when mousing over the widget:

  1. Add two combo boxes to the third layout located at the bottom. We will leave them empty for now:

  1. Right-click on the Convert button and select Go to slot…. A window will pop up, asking you to select an appropriate signal. Let's keep the default clicked() signal as the selection and click OK. Qt Creator will automatically add a slot function to both mainwindow.h and mainwindow.cpp.
  2. Open mainwindow.h and make sure the following headers are being added to the top of the source file:
#include <QMainWindow>
#include <QDoubleValidator>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QMessageBox>
  1. Add another slot function, called finished():
private slots:
void on_convertButton_clicked();
void finished(QNetworkReply* reply);
  1. Add two variables under the private label:
private:
Ui::MainWindow *ui;
QNetworkAccessManager* manager;
QString targetCurrency;
  1. Open the mainwindow.cpp file. Add several currency short codes to both combo boxes in the class constructor. Set a validator to the Line Edit widget on the left so that it can only accept inputs that are numbers. Initialize the network access manager and connect its finished() signal to our finished() slot function:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
QStringList currencies;
currencies.push_back("EUR");
currencies.push_back("USD");
currencies.push_back("CAD");
currencies.push_back("MYR");
currencies.push_back("GBP");
  1. We continue from the previous code and insert the currency short forms into the combo boxes. Then, we declare a new network access manager and connect its finished signal to our custom slot function:
    ui->currencyFrom->insertItems(0, currencies);
ui->currencyTo->insertItems(0, currencies);
QValidator *inputRange = new QDoubleValidator(this);
ui->amountFrom->setValidator(inputRange);
manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished, this, &MainWindow::finished);
}
  1. Define what will happen if the Convert button is clicked by the user:
void MainWindow::on_convertButton_clicked() {
if (ui->amountFrom->text() != "") {
ui->convertButton->setEnabled(false);
QString from = ui->currencyFrom->currentText();
QString to = ui->currencyTo->currentText();
targetCurrency = to;
QString url = "http://data.fixer.io/api/latest?base=" + from + "&symbols=" + to + "&access_key=616e8b801a222f144a9460b5e6942ca4";

  1. Start the request by calling get():
        QNetworkRequest request= QNetworkRequest(QUrl(url));
manager->get(request);
} else {
QMessageBox::warning(this, "Error", "Please insert a value.");
}
}
  1. Define what will happen when the finished() signal is triggered:
void MainWindow::finished(QNetworkReply* reply) {
QByteArray response = reply->readAll();
qDebug() << response;
QJsonDocument jsonResponse = QJsonDocument::fromJson(response);
QJsonObject jsonObj = jsonResponse.object();
QJsonObject jsonObj2 = jsonObj.value("rates").toObject();
double rate = jsonObj2.value(targetCurrency).toDouble();
  1. Continue to write the code from the preceding code, as shown in the following:
    if (rate == 0)
rate = 1;
double amount = ui->amountFrom->text().toDouble();
double result = amount * rate;
ui->amountTo->setText(QString::number(result));
ui->convertButton->setEnabled(true);
}
  1. Compile and run the project, and you should get a simple currency converter that looks like this:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset