Course: CPEN6126 – Cross Platform Application Development
Effective Period: September 2021
Qt Foundation
Learning Outcomes
At the end of this session, student will be able to:
• LO1 EXPLAIN fundamental concepts of Cross Platform
Application Development
Sub Topics
• Part I:
– Qt Project Structure
– MainWindow Structure
– Using QDialog
– Signal and Slot
– Emitting a custom signal using lambdas
• Part II:
– Accessing Files using Qt
– Accessing HTTP resources using Qt
– Parsing JSON using Qt
Part I
Qt Project Structure
• Every Qt project have .pro Qt Project Configuration file
• This file used by qmake tools to produce platform specific Makefile
• Makefile will compile using standard make or cmake build tools
• .pro contain:
– Qt module used (such as: core, gui, widget, sql, network)
– Target name (executable name, ie: todo, todo.exe)
– Project template (app, lib, etc)
– Sources, headers, forms
– Conditional compilation: can compile to specific Qt version,
platform or debug| release mode
– Specific setting to compiler: CONFIG +=c++14
Qt Project Structure
• Example project generated for MainWindow wizard:
QT += core gui
CONFIG += c++14
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = todo
TEMPLATE = app
SOURCES += main.cpp \
MainWindow.cpp
HEADERS += MainWindow.h \
FORMS += MainWindow.ui \
MainWindow Structure
• Qt wizard generate 3 file for each Qt Widget Application:
– Header file .h
– Cpp file .cpp
– Form file: .ui
• Example for MainWindow project that have label and button:
– Header file: mainwindow.h class declaration
– Cpp file: mainwindow.cpp class implementation
– Form file: mainwindow.ui used by qt designer to
visually layout UI component
MainWindow Structure:
mainwindow.h
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
MainWindow Structure:
mainwindow.cpp
#include "MainWindow.h"
#include "ui_MainWindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
Qt Designer Interface
Using QDialog
• Easy way for user input:
#include <QInputDialog>
...
void MainWindow::addTask()
{
bool ok;
QString name =
QInputDialog::getText(this,
tr("Add task"),
tr("Task name"),
QLineEdit::Normal,
tr("Untitled task"), &ok);
if (ok && !name.isEmpty()) {
qDebug() << "Adding new task";
Task* task = new Task(name);
mTasks.append(task);
ui->tasksLayout->addWidget(task);
}
}
Signal and Slot
• signal is a message sent by an object
• slot is a function that will be called when this signal is triggered
• The connect function specifies which signal is linked to which slot
• Here is why you will love Qt signals and slots:
– A slot remains an ordinary function, so you can call it yourself
– A single signal can be linked to different slots
– A single slot can be called by different linked signals
– A connection can be made between a signal and a slot from different
objects, and even
– between objects living inside different threads
Signal and Slot
• Syntax of a Qt connection:
• Example:
– sender: Object that will send the signal. In our example, the
QPushButton named addTaskButton is added from the UI designer.
– &Sender::signalName: Pointer to the member signal function, Here,
we want do something when the clicked signal is triggered.
Signal and Slot
• receiver: Object that will receive and handle the signal.
In our case, it is the Qapplication object created in
main.cpp.
• &Receiver::slotName: Pointer to one of the
receiver's member slot functions. In this example, we use
the built-in quit() slot from QApplication, which
will exit the application.
• You can connect a signal to another signal. The second signal
will be emitted when the first one is triggered.
Emitting a custom signal using lambdas
• Qt support lambda function, features in C++11
Part II
Accessing Files using Qt
• Qt provides us with classes that allow us to easily access the
filesystem regardless of the type of operating system
• Qt Class for file access:
– QIODevice : general class for byte stream
– QFile: subclass of QIODevice for file access
– QTcpSocket: subclass of QIODevice for TCP
communication
Accessing Files using Qt
• File Access Mode:
– QIODevice::ReadOnly: This is used for read-only access.
– QIODevice::WriteOnly: This is used for write-only access.
– QIODevice::ReadWrite: This is used for read-and-write access.
– QIODevice::Append: This is used to only append to the file.
– QIODevice::Truncate: This is used to truncate the file, discarding all
previous
– contents before writing.
– QIODevice::Text: This is used to treat the file as text, converting new-line
– characters to the platform representation during reading and writing.
– QIODevice::Unbuffered: This is used to bypass any buffering of the input
and
– output.
Accessing Files using Qt
• Example: open file and print out the contents
Accessing HTTP resources using Qt
• Qt support to use http protocol through QHttp class
• Add QT+= network in .pro
• Example http request:
Parsing JSON using Qt
1. First, we must include the headers related to JSON classes:
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
2. After that, we will try and parse the preceding JSON data, which looks
something like this when converted into QString format:
QString jsonString =
"{\"firstName\": \"John\",\"lastName\":
\"Smith\",\"age\": 42,\"address\":
{\"streetAddress\": \"14 2nd
Street\",\"city\": \"New
York\",\"state\": \"NY\",\"postalCode\":
\"10021-3100\"},\"phoneNumbers\":
[{\"type\": \"home\",\"number\":
\"212 686-7890\"},
{\"type\": \"mobile\",\"number\": \"321
456-7788\"}]}";
Parsing JSON using Qt
3. Next, we will parse the data by first converting it into a QJsonDocument
object,then obtain the QJsonObject object by calling the
QJsonDocument::fromJson() function.
4. Then, we convert the QJsonObject into a QVariantMap before we are
able to
obtain the data we need from it:
QJsonDocument doc =
QJsonDocument::fromJson(jsonString.toUtf8());
QJsonObject obj = doc.object(); // Get the json
object
QVariantMap map = obj.toVariantMap(); // Convert json
object to
variant map
qDebug() << map["firstName"].toString(); // Obtain
firstName data
Parsing JSON using Qt
Parsing JSON using Qt
Learning Activity
1. Create Qt Application to download image from internet, and
save to file
2. Create Qt Application to parse Json string
References
• Guillaume Lazar, Robin Penea, 2018. “Mastering Qt 5: Create
stunning cross-platform applications using C++ with Qt Widgets
and QML with Qt Quick”, Packt Publishing Ltd, Birmingham,
ISBN:978-1-78899-539-9, Chapter: 1
• Lee Zhi Eng, Ray Rischpater, 2020, "Application Development
with Qt Creator: Build cross-platform applications and GUIs
using Qt 5 and C++”, 3rd Edition, Packt Publishing Ltd ,
Birmingham, ISBN: 978-1-78995-175-2, Chapter 3
• New Signal and slot: https://wiki.qt.io/New_Signal_Slot_Syntax
• Qt Signal and Slot:
https://www.youtube.com/watch?v=DlGGLRmRH0s
• C++ Qt 64 - QHttp download files from the web with ease:
https://www.youtube.com/watch?v=dw50MnqH-Qo