Currency conversion

In this example, we will learn how to create a simple currency converter using Qt, with the help of an external service provider called Fixer.io.

How to do it…

Make yourself a currency converter with these simple steps:

  1. We start by opening Qt Creator and creating a new Qt Widgets Application project from File | New File or Project.
  2. Next, open up the project file (.pro) and add the network module to our project:
    QT += core gui network
  3. After that, open up mainwindow.ui and remove the menu bar, tool bar, and status bar from the UI.
  4. Then, add three horizontal layouts, a horizontal line, and a push button to the canvas. Once they're all placed, left-click on the canvas and follow by clicking the Lay Out Vertically button above the canvas. Then, set the label of the push button as Convert. The UI should now look something like this:
    How to do it…
  5. After that, add two labels to the top layout and set the text of the left one as From:, followed by the right one as To:. Right after that, add two line edit widgets to the second layout and set both their default values as 1:
    How to do it…
  6. Before we proceed to add the last batch of widgets to the last layout, let's select the line edit on the right and enable the readOnly checkbox located in the property pane:
    How to do it…
  7. Other than that, we also must set its cursor property to Forbidden so that users know it's not editable when mousing over the widget:
    How to do it…
  8. Once you're done with that, let's add two combo boxes to the third layout located at the bottom. We will just leave them empty for now:
    How to do it…
  9. After that, right-click on the Convert button and select Go to slot…. A window will now 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 now automatically add a slot function for you to both mainwindow.h and mainwindow.cpp.
  10. Next, open up 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>
  11. Then, we need to add another slot function called finished():
    private slots:
      void on_convertButton_clicked();
      void finished(QNetworkReply* reply);
    
  12. Besides that, we also need to add two variables under the private label:
    private:
      Ui::MainWindow *ui;
      QNetworkAccessManager* manager;
      QString targetCurrency;
    
  13. Once you're done, let's open up mainwindow.cpp this time. We will add several currency shortcodes to both the combo boxes in the class constructor. We also set a validator to the line edit widget on the left so that it can only accept inputs that are numbers. Lastly, we also 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");
    
      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, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
    }
  14. After that, we define what will happen if the Convert button is being 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://api.fixer.io/latest?base=" + from + "&symbols=" + to;
        QNetworkRequest request= QNetworkRequest(QUrl(url));
        manager->get(request);
      }
      else
      {
        QMessageBox::warning(this, "Error", "Please insert a value.");
      }
    }
  15. Lastly, 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();
      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);
    }
  16. Compile and run the project now and you should be able to get a simple currency converter that looks like this:
    How to do it…

How it works...

Similar to the previous example we saw, which uses an external program to achieve a specific task, this time we use an external service provider who provided us with an open Application Programming Interface (API) that is free for all and easy to use.

This way, we don't have to think about the method to retrieve the latest currency rate. Instead, the service provider has already done the job for us and we just have to send a polite request and ask for it. Then, we just wait for the response from their server and process the data according to our intended purposes.

There are quite a few different service providers you can choose from besides Fixer.io (http://fixer.io). Some are free but without any advanced features; some provide you with additional functionalities, although they come at a premium price. Some of these alternatives are Open Exchange Rate (https://openexchangerates.org), Currencylayer (https://currencylayer.com), Currency API (https://currency-api.appspot.com), XE Currency Data API (http://www.xe.com/xecurrencydata), and Jsonrates (http://jsonrates.com).

There's more…

Besides currency exchange rates, you can also use this method to do other more advanced tasks that are perhaps too complicated to do by yourself, or are simply impossible to access unless you use the services provided by specialists, for example, programmable Short Message Service (SMS) and voice services, web analytics and statistic generation, online payment gateways, and the list goes on. Most of these services are not free, but you can easily achieve those functions in minutes without even setting up the server infrastructure, backend system, and whatnot; it's definitely the cheapest and fastest way to get your product up and running without much hassle.

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

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