QT Programming

Using the QT Framework with C++

1. QT Programming Saidu Sheik
2. Before We Start  Saidu Sheik  Participants – What do you do? – Why are you taking this course?  Course details – Theory + practice 2 ISTQB
3. Trainer  Expertise in application programming, developing, maintaining and modifying programs.  8 years of experience in product development using C++ with the Qt framework.  Expertise in GUI design and development.  I have a perfect knowledge of C++ advanced concepts like C++ 11,14 and 17.  Working knowledge on Multithread programming and plug-ins development.  Knowledge on Cloud Computing.  Knowledge on C, C++, Data Structures, Java, Linux, MYSQL and PL/SQL.  Knowledge on SVN, Source Safe, Jira and Code collaborator. 3 I have ISTQB a very good knowledge on Qt Models and Views.
4. Before we begin – Schedule  Starts 09:00  Ends 17:00  Lunch – 60 mins  Break 4 – 10-15 mins AM – 10-15 mins PM ISTQB
5. Course details Course title: QT Programming  Scope: – By the end of this training, participants will have the necessary knowledge and practice to develop their own C++ application using QT – Trainer evaluation sheet  Sent to your email inboxes – Course certificates of completion  Sent to your email inboxes 5 ISTQB
6. Qt History Meet Qt  Qt Was initially developed by two persons ,Haavard Nord (CEO), and EirikChambe(President) in early 90.  Both graduated from Norwegian Institute of Technology in Computer Science and formed Throlltech Inc. in 1994.  In January 2008, Trolltech was acquired by Nokia.  In October 2011, Qt was opened to the community through qtproject.org.  In August 2012, Qt was acquired by Digia.  In September 2014, Qt activities were transferred to The Qt Company.  The Qt Company is not the only company developing Qt.  Many other organizations and individuals contribute.  From bug fixes to entire modules. 6 ISTQB
7. Who uses Qt  European Space Agency  Google Earth  Skype  KDE (Operating System Dist. on Linux)  Adobe Photoshop Album (graphics)  Autodesk Maya (Animation)  VLC (Video)  Panasonic and Thales IFE (Airline)  Navico (Navigation)  Eykona (healing process monitor)  Barco (Medical Imaging) Michelin, Intel, HP, Samsung, Blackberry, ABB, AMD, Epson, HONDA, Cannon, … 7 ISTQB
8. Benifits  Cross platform GUI framework  Produce compact, high-performance applications.  Focus on innovation, not infrastructure coding.  Choose the license that fits you.  Commercial, LGPL or GPL  Count on professional services, support and training. 8 ISTQB
9. Tools  Qt Creator : Cross platform IDE  Qt Designer: GUI layout and forms builder  QtLinguest: Internationalization toolset  Qt Assist: Customizable documentation reader  QtQmake: Cross platform build tool  Plugin for other IDE: Integration with Visual Studio and Eclipse  Configure: Tool to configure Qt on any specific platform  Qt SDK: Rich C++ library 9 ISTQB
10. Qt Modular Class Library 10 ISTQB
11. Hello Qt  Main.cpp 11 ISTQB
12. Project file (.pro) Sample .pro file  Project file contains all the information required by qmake. 12 ISTQB
13. Project file (.pro) 13 ISTQB
14. qmake tool  qmake tool  It automates the generation of make files.  qmake generates the make files based on the information in a project file.  qmake -project (Creates default project file based on directory content)  qmake –t vclib (for library projects)  qmake –t vcapp(for application projects) 14 ISTQB
15. QCoreApplication • QCoreApplication contains the main event loop, where all events from the operating system (e.g., timer and network events) and other sources are processed and dispatched. • This class is used by non-GUI applications to provide their event loop. • Pass command line arguments • Provides an event-loop to process and dispatch events • Internationalization - QObject::tr() • Access to application path 15 ISTQB
16. QApplication  The QApplication class manages the GUI application's control flow and main settings.  It initializes the application with the user's desktop settings such as palette(), font() and doubleClickInterval().  It performs event handling, meaning that it receives events from the underlying window system and dispatches them to the relevant widgets. By using sendEvent() and postEvent() you can send your own events to widgets.  It parses common command line arguments and sets its internal state accordingly.  It defines the application's look and feel, which is encapsulated in a QStyle object. This can be changed at runtime with setStyle().  Mouse cursor handling : setOverrideCursor() 16 ISTQB
17. How much C++ do we need to know?  Objects and classes • Declaring a class, inheritance, calling member functions, etc.  Polymorphism • That is virtual methods  Operator overloading  Templates • For the container classes only  No ... • ... RTTI • ... sophisticated templates • ... exceptions thrown • ... 17 ISTQB
18. Qt Modules  QtCore,  QtGui  QtWidgets  QtQuick  QtXml  QtSql  QtNetwork  QtTest  ... 18 ISTQB
19. How to enable to Qt Modules? QT += network By default qmake projects use QtCore and QtGui. All classes and modules in qt has a header file. #include <Qstring> #include<QtCore> 19 ISTQB
20. Qt’s C++ Object Model - QObject  QObject is the heart of Qt's object model.  The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots.  Properties  Event Handling  Memory Management  QObject has no visual representation. 20 ISTQB
21. Object tree  QObjects organize themselves in object trees. • Based on parent-child relationship  QObject(QObject *parent = 0) • Parent adds object to list of children. • Parent owns children.  Construction/Destruction • Tree can be constructed in any order. • Tree can be destroyed in any order. • If object has a parent, object is first removed from parent. • If object has children, each child is deleted first. • No object is deleted twice. 21 ISTQB
22. QWidget  Derived from QObject  Base class for all user objects  QWidget without parent = MainWindow  Container Widget :  Aggregates other child widgets.  Use layout for aggregation Example: 22 ISTQB
23. Signals and slots  Three approaches to connect signals and slots • Function pointers • SIGNAL/SLOT macros • Function objects 23 ISTQB
24. Connect – function pointers  Function pointers connect( const QObject * sender, PointerToMemberFunction signal, const QObject * receiver, PointerToMemberFunction method )  Example: QSlider *slider = new QSlider( Qt::Horizontal ); QSpinBox *spin = new QSpinBox; QObject::connect( slider, &QSlider::valueChanged, spin, &QSpinBox::setValue ); 24 ISTQB
25. Connect - Macros  SIGNAL/SLOT macros connect( const QObject * sender, const char * signal, const QObject * receiver, const char * method )  Example: QSlider *slider = new QSlider( Qt::Horizontal ); QSpinBox *spin = new QSpinBox; QObject::connect( slider, SIGNAL(valueChanged(int)), spin, SLOT(setValue(int)) ); 25 ISTQB
26. Function Objects  Lamba functions  Functors  Standalone functions 26 ISTQB
27. Types of connections  Auto connection  Direct connection  Queued connection  Signal to signal  One signal can connect to multiple slots  Multiple signals can connect to one slot  Disconnect signals using Disconnect  Track signals using ConnectNotify and DisconnectNotify 27 ISTQB
28. Exercise  Implement all the methods related to below UI using Signals and slots  Add details in QTable Widget ( Use QTableWidgetItem) 28 ISTQB
29. Qt Events Objectives  Understand the concept of events  Understand the difference between events and signal/slots  Be able to implement event handling  Understand the role of events in painting  Understand the role of event filters and be able to use them  Understand the concept of event propagation  Learn how to post/send events  Be able to create/send/handle custom events 29 ISTQB
30. Qt Events  In Qt, events are objects that represent things that have happened either within an application or as a result of outside activity that the application needs to know about.  When an event occurs, Qt creates an event object to represent it and delivers it to a particular instance of QObject (or a subclass) by calling its {{event()} function.  This function calls an event handler for the specific event.  Three categories:  Spontaneous events are generated by the window system. They are put in a system queue and processed one after the other by the event loop.  Posted events are generated by Qt or by the application. They are queued by Qt and processed by the event loop.  Sent events are generated by Qt or by the application, but they are sent directly to the target object.  Events are useful when we write our own widgets or we want to modify the behavior of existing widgets. 30 ISTQB
31. Key Events •Key events are handled by reimplementing keyPressEvent() and keyReleaseEvent(). 31 ISTQB
32. Key Events 32 ISTQB
33. Key Events 33 ISTQB
34. Timer Events  Timer events allow applications to perform processing at regular time intervals  The QTimer class provides an interface for timers. To use it: – Create a QTimer – connect its timeout() signal to the appropriate slots – call start() – From then on it will emit the timeout() signal at constant intervals. 34 ISTQB
35. Difference between events and signal/slots Signals and slots are used instead of events:  To communicate between components.  In cases where there is a well-defined sender and receiver. » Example: a button and a slot to handle clicks  To describe high level logic and control flow. Events are more low level:  For some events, there is no sender in Qt. » Example: redraw, keyboard and mouse events. Developers can create custom events if they need to. 35 ISTQB
36. Core classes  String Handling  Container Classes  File Handling  Variants and Properties 36 ISTQB
37. QString Creation 37 ISTQB
38. Text Processing with QString 38 ISTQB
39. Text Processing with QString 39 ISTQB
40. Text Processing with QString Strings can be tested with:  length() » returns the length of the string  endsWith() and startsWith() » tests whether string starts or ends with another string  contains() » returns whether the string matches a given expression  count() tells you how many times.  indexOf() and lastIndexOf() » searches for next matching expression, and return its index. Expression can be characters, strings, or regular expressions. 40 ISTQB
41. QStringList  QString::split() and QStringList::join()  split one string or join many strings using a substring  QStringList::replaceInStrings()  search/replace on all strings in a list  QStringList::filter()  returns list of items matching given pattern or substring 41 ISTQB
42. Container Classes 42 ISTQB
43. Using Container Classes 43 ISTQB
44. Algorithm Complexity 44 ISTQB
45. File Handling 45 ISTQB
46. Reading/Writing a file 46 ISTQB
47. Sample application on file writing and reading  Provide implementation for below Save button by writing details in a text file. 47 ISTQB
48. QVariant 48 ISTQB
49. Custom types & QVariant  Q_DECLARE_METATYPE what is use of this macro  How to store custom types in QVariant  How to read custom data from QVariant  Write an example program to show this 49 ISTQB
50. Qvariant Usages 50 ISTQB
51. Widgets Top level and child widgets 51 ISTQB
52. Types of widgets  Qlabel  QLineEdit  QTextEdit  QAbstractButton  QPushButton  QRadioButton  QCheckBox  QButtonGroup  QSlider  QProgressBar  QSpinBox 52 ISTQB
53. Types of widgets  QGroupBox  QTabWidget  QComboBox  QListWidget  QTableWidget  QTreeWidget  QStackedWidget  QDateTimeEdit  QCalendarWidget 53 ISTQB
54. Layout Management Classes  QHBoxLayout  Lines up widgets horizontally  QVBoxLayout  Lines up widgets vertically  QGridLayout  Arranges the widgets in a grid  QFormLayout  Lines up a (label, widget) pairs in two columns. 54 ISTQB
55. QHBoxLayout and QVBoxLayout  Layouts example programs 55 ISTQB
56. QGridLayout and QFormLayout 56 ISTQB
57. Painting  QPainter provides highly optimized functions to do most of the drawing GUI programs require.  It can draw everything from simple lines to complex shapes like pies and chords.  It can also draw aligned text and pixmaps. Normally, it draws in a "natural" coordinate system, but it can also do view and world transformation.  QPainter can operate on any object that inherits the QPaintDevice class.  The core functionality of QPainter is drawing, but the class also provide several functions that allows you to customize QPainter's settings and its rendering quality, and others that enable clipping. 57 ISTQB
58. Painting  Override paintEvent(QPaintEVent*) 58 ISTQB
59. Dialogs Modal Dialogs  The QDialog class is the base class of dialog windows.  QDialogs may be modal or modeless.  A modal dialog is a dialog that blocks input to other visible windows in the same application.  Dialogs that are used to request a file name from the user or that are used to set application preferences are usually modal. Modal  Dialogs can be application modal (the default) or window modal.  When an application modal dialog is opened, the user must finish interacting with the dialog and close it before they can access any other window in the application.  Window modal dialogs only block access to the window associated with the dialog, allowing the user to continue to use other windows in an application.  The most common way to display a modal dialog is to call its exec() function.  Example: Configuration Dialog 59 ISTQB
60. Dialogs Modeless Dialogs  A modeless dialog is a dialog that operates independently of other windows in the same application. Find and replace dialogs in wordprocessors are often modeless to allow the user to interact with both the application's main window and with the dialog.  Modeless dialogs are displayed using show(), which returns control to the caller immediately.  Example:Find/Search Dialog 60 ISTQB
61. Dialogs  QFileDialog  QMessageBox  QColorDialog  QFontDialog  QErrorMessage 61 ISTQB
62. Qt Designer  Design UI forms visually  Visual editor for  Signal/slot connections  Actions  Tab handling  Buddy widgets  Widget properties  Integration of custom  widgets  Resource files 62 ISTQB
63. UI Form Files  Forms stored in xml file (dialog.ui)  uic tool read this dialog.ui file and generates ui_dialog.h class Ui_Dialog { public: QLabel* label; ... void setupUi(QWidget *) { } }; 63 ISTQB
64. The model/view architecture 64 ISTQB
65. The Model/View Architecture  MVC stands for Model, View and Controller.  Model is responsible for maintaining application data and business logic.  View is a user interface of the application, which displays the data.  Controller handles user's requests and renders appropriate View with Model data.  Item - > Imaginary unit of data in model.  Index-> used to locate item in model. 65 ISTQB
66. How to use existing models QFileSystemModel  This class provides access to the local filesystem, providing functions for renaming and removing files and directories, and for creating new directories.  In the simplest case, it can be used with a suitable display widget as part of a browser or filter.  A directory model that displays the contents of a default directory is usually constructed with a parent object:  QFileSystemModel *model = new QFileSystemModel; model->setRootPath(QDir::currentPath());  A tree view can be used to display the contents of the model QTreeView *tree = new QTreeView(splitter); tree->setModel(model); 66 ISTQB
67. Models 67 ISTQB
68. View Classes  QAbstractItemView – Abstract base class for all views  QListView  QTableView  QTreeView  QHeaderView  QColumnView 68 ISTQB
69. Model Classes  QAbstractItemModel – Generic model class  QAbstractListModel – One dimensional list » QStringListModel – works on string list  QAbstractTableModel – works on two dimensional tables  QAbstractProxyModel – Sort, Filter, Reording.  QFileSystemModel – model for local file system 69 ISTQB
70. QAbstractListModel  Create a class derived from QAbstractListModel  Reimplement int rowCount() and QVariant data()  For edit support, reimplement Qt::ItemFlags flags() and setData() 70 ISTQB
71. QAbstractTableModel Populate Name and Phone in QTableView using QabstractTableModel  Everything from QAbstractListModel applies here too  In addition reimplement columnCount() 71 ISTQB
72. Handling Data Changes  Inform the view of changes in the model:  QAbstractItemModel provides signals to inform the views when its contents change : dataChanged(), headerDataChanged()  Don't forget to emit the right signal when you change data in the model, to make sure the views will be properly updated. For example, you should emit dataChanged() from setData(). 72 ISTQB
73. Handling Structural changes  Structural changes in the model follow a transactional approach: begin/end methods. For instance, when adding new rows:  1. Call beginInsertRows().  2. Insert the new rows in the data storage.  3. Call endInsertRows(). 73 ISTQB
74. QAbstractItemModel  Using QAbstractItemModel:  Everything from QAbstractTableModel applies here, too.  Implement QModelIndex index(row, column, parent), where parent is  itself a model index.  Implement QModelIndex parent(QModelIndex).  Indexes can be created using the protected method  QAbstractItemModel::createIndex(), which is overloaded to take either  an integer index or a void pointer (usually internal data pointer to your data  structure). 74 ISTQB
75. Proxy Models  Do sorting , filtering or other data processing tasks.  All standard proxy models are derived from the QAbstractProxyModel class.  Proxy models that filter or sort items of data from a source model should be created by using or subclassing QSortFilterProxyModel.  Set proxy model to view  TableModel *model = new TableModel();  QListView *view = new QListView(parent);  QSortFilterProxyModel *proxy = new QSortFilterProxyModel(parent);  proxy->setSourceModel(model);  view->setModel(proxy); 75 ISTQB
76. XML  Qt XML Simple XML streamreader and writer  A well formed XML parser using SAX2 (Simple API for XML) interface, as well as DOM level 2 (Document Object Model)  XMLPattern module  An implementation of the XQuery standard  Enable users to query XML files similar to SQL  Semantics for value assignment, filtering, and simple operations  Fully controllable out formatting XSLT support  To include QtXml add QT += xml in .pro file. 76 ISTQB
77. Writing XML 77 ISTQB
78. Reading XML QFile xmlFile ...; QDomDocument doc; doc.setContent(&xmlFile); // retrieve root element QDomElement root = doc.documentElement(); QDomNode node = root.firstChild(); while(!node.isNull()) { // always test a node QDomElement element = node.toElement(); if(!element.isNull()) { // test if node is an element qDebug() << element.tagName(); } node = node.nextSibling(); } 78 ISTQB
79. Qt Plugins  Qt provides two APIs for creating plugins:  A high-level API for writing extensions to Qt itself: custom database drivers, image formats, text codecs, custom styles, etc.  A low-level API for extending Qt applications.  Writing a plugin involves these steps:  Declare a plugin class that inherits from QObject and from the interfaces that the plugin wants to provide.  Use the Q_INTERFACES() macro to tell Qt's meta-object system about the interfaces.  Export the plugin using the Q_PLUGIN_METADATA() macro.  Build the plugin using a suitable .pro file. 79 ISTQB
80. QSettings  Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in property list files on macOS and iOS. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.  Configure Qsettings QCoreApplication::setOrganizationName("CompanyName"); QCoreApplication::setOrganizationDomain("CompanyName.com"); QCoreApplication::setApplicationName("Application Name"); QSettings settings; settings.setValue(“pdm/log”,4); int value = settings.value(“pdm/log”).toInt(); *Values stored as QVariant. 80 ISTQB
81. Interprocess Communication  QNetworkAccessManager  QNetworkRequest  QNetworkReply  Add QT += network in .pro file  The QNetworkAccessManager class allows the application to send network requests and receive replies.  Once a QNetworkAccessManager object has been created, the application can use it to send requests over the network. A group of standard functions are supplied that take a request and optional data, and each return a QNetworkReply object. The returned object is used to obtain any data returned in response to the corresponding request.  Manager = new QNetWorkAccessManager(this);  manager->get(QNetworkRequest(QUrl("http://bogotobogo.com"))); 81 ISTQB
82. Graphics View  QGraphicsView - The QGraphicsView class provides a widget for displaying the contents of a QGraphicsScene. QGraphicsScene scene; scene.addText("Hello, world!"); QGraphicsView view(&scene); view.show();  QGraphicsScene – Container for Graphics items.  Items can exists in only one scene at a time.  Important methods: addItem(),Items(),selectedItems()  QGraphicsItem  Uses MVC design pattern 82 ISTQB
83. THANK YOU 83 ISTQB
No comments...
none

Related Slides

  •   Offered Courses Qt