Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Qt 5 - C++ and Widgets


Published on

Qt 5 programming with C++. This is Qt traditional way to develope desktop applications.

Published in: Technology
  • Login to see the comments

Qt 5 - C++ and Widgets

  1. 1. Qt5 Qt 5 project: Tools: Docs: Qt Commercial: Lectures by Juha Peltomäki
  2. 2. 5 Framework ● Qt5 – Cross Platform Framework – Qt5: – Old Qt4:
  3. 3. A cross-platform application development framework ● ● ● ● Using Qt, you can write applications and user interfaces once, and deploy them across many OS. In June 2008 Nokia acquired Trolltech ASA to enable the acceleration of their cross-platform software strategy for mobile devices and desktop applications. In August 2012 Digia announced its plans to acquire the Qt technology and business from Nokia. December 19, 2012 — Digia has announced the launch of Qt 5. – ”Qt 5 delivers a step function increase in performance, functionality and ease of use and will be the platform on which full Android and iOS support will be delivered during the coming year."
  4. 4. Qt5 overview ● ● cross-platform, graphical, application development toolkit run applications on Windows, Mac OS X, Linux, and different embedded/mobile OSs – ● embedded Linux like Android, iOS, Blackperry, also some RTOS LInux OS like QNX are supported licensed under a professional (commercial, closed source) and GPL/ LGPL (open source)
  5. 5. Qt5 Tools ● Qt Creator as a main IDE tools – ● Qt Creator should be the first choice for Qt beginners who want to get up and running quickly with Qt framework Qt Creator includes – – Qt Linquist for localization – ● Qt Designer for easy UI designing and building qmake to build apps to different target platforms Qt5 development tools: –
  6. 6. Qt libraries ● GUI and Widget libraries ● Networking ● XML ● SQL ● Container classes ● Multi-threading ● Animation ● Scripting ● QtQuick / QML
  7. 7. Qt Creator ● Qt Creator - Originally Published at Oct '08 – a lightweight IDE – supports developing for different platforms – open and easily extendable – Context-sensitive help – Creating, editing and navigating code – supports the GNU compiler (gcc) and debugger – supports qmake build system
  8. 8. Qt Designer ● GUI tools for rapid software development ● Separate easily UI from model classes – Much easier than manual UI coding – UI saved in XML files – Support for signals and slots mechanism – Support QML
  9. 9. Qt programming environment ● ● ● ● Originally C++ based Framework Qt5 Supports also QML with JavaScript with support to C++ "backend" components supports single-source cross-platform development on Windows, Mac and Linux desktop and different embedded and mobile platforms (Blackberry 10, Android etc.) KDE Desktop environment is based on Qt Framework
  10. 10. Links for Learning Qt ● ● Book Online: ”The Art of Building Qt Applications”: If you want to program purely in Qt/C++ and design your interfaces in code without the aid of any design tools, take a look at the Qt Tutorials.
  11. 11. Qt5 - Getting started ● You can select 2 different approach to develop your Qt5 applications ● These are ● Qt5 Widgets – C++ based, traditional way ● ● ● QML, declarative UI language with JavaScript support
  12. 12. Qt Widgets ● The Qt Widgets Module provides a set of UI elements to create classic desktop-style user interfaces ● – QWidget class provides the basic capability to render to the screen, and to handle user input events.
  13. 13. Qt Quick (QML) ● QtQuick and QML (Declarative UI language) – QtDeclarative creates a JavaScript runtime that QML runs with a Qt/C++ application ● ● ● can call C++ from QML and visa versa QML is easy enough for designers also, so UI can be prototyped very quickly with QML You can separate backend code from UI code easily so it enforces to use Model/View architecture in your application
  14. 14. Qt Core Some Qt Core Source material: ● ● ● ● ● ● Classes: Qt Core: Object model: Object trees: MOC:
  15. 15. QtCore library Basic data types are supported ● ● ● ● ● Qt supports C++ basic types and basic classes Qt's own class types are used (QString, QVector etc.) in most cases basic data collection structures (vector, list, maps) are defined by Qt Even the basic data types are predefined by Qt Well-defined parent, child relationship between components
  16. 16. Qt is dynamic ● Standard C++ has efficient run-time support but very static model ● Qt's Object model adds more dynamic model for creating GUI and possible to add dynamic properties using moc compiler
  17. 17. Qt's Object model ● ● ● ● flexibility of Qt is basicly implemented in the Qt's Object Model. Qt features are implemented based on QObject using standard C++. Qt has it's own Meta-Object Compiler (moc). C++/GUI programming needs more flexibility and Qt provides it.
  18. 18. Qt's features ● ● hierarchical object trees that organize object ownership in a natural way efficient object communication (signals and slots) ● dynamic properties of Object ● powerful events and event filters
  19. 19. Qt's features ● guarded pointer (QPointer) is automatically set to 0 when the referenced object is destroyed ● ● ● normal C++ pointers become "dangling pointers" in such cases dynamic cast (qobject_cast) that works across library boundaries with every class inherit from QObject interval driven timers that make it possible to elegantly integrate many tasks in an eventdriven GUI
  20. 20. QObject – the base class of Qt's Object hierarchy ● Has Unique name (QObject::objectName()) ● has a location in an object hierarchy ● ● can be connected to any other Qt Objects to emit/receive signals new dynamic properties can be added to it at runtime – Note! QObject and all subclasses of QObject have their copy constructor and assignment operator disabled.
  21. 21. Qt data types ● ● QtGlobal header file declares several type definitions that guarantee a specified bit-size on all platforms supported by Qt for various basic types, for example qint8 which is a signed char guaranteed to be 8-bit on all platforms supported by Qt. Source:
  22. 22. QtCore Module ● ● ● The QtCore module contains core functionality to create business logic Some of most important and useful classes are listed below: QtCore classes ● ● ● QMetaObject - Contains meta-information about Qt objects QObject - The base class of all Qt objects QVariant - Acts like a union for the most common Qt data types
  23. 23. QtCore Module continues ● QCoreApplication - Event loop for console Qt applications. For UI applications see QApplication class from QtGui module – ● ● Event loop is started with QCoreApplication::exec and uses exit() to exit from the main event loop. QEvent - is The base class of all event classes. Event objects contain event parameters QMetaObject class contains meta-information ● Also there is QtConcurrent namespace high-level APIs that make it possible to write multi-threaded programs more easily.
  24. 24. QtCore - container classes ● ● ● ● ● QHash - Template class that provides a hash-tablebased dictionary QLinkedList lists Template class that provides linked QList - Template class that provides lists QMap - Template class that provides a skip-listbased dictionary QMultiHash - Convenience QHash subclass that provides multi-valued hashes
  25. 25. QtCore container classes ● ● ● ● ● QMultiMap - Convenience QMap subclass that provides multi-valued maps QSet - Template class that provides a hash-tablebased set QStack - Template class that provides a stack QVector - Template class that provides a dynamic array QVectorIterator - Java-style const iterator for QVector and QStack
  26. 26. QtCore char/string classes ● ● ● ● ● ● QString - Unicode character string (stores a string of 16-bit QChars) QStringList - List of Unicode strings QByteArray – store raw bytes or traditional 8-bits strings (const char *) QChar - 16-bit Unicode character QLatin1String - wrapper for Latin-1/ASCII encoded 8-bit string (see QString::toLocal8Bit ()) QRegExp - regular expression support for QStrings
  27. 27. QtCore - multithread classes ● QRunnable - base class for all runnable objects ● QThread is for Platform-independent threads ● QThreadPool manages a collection of Qthreads ● Note! QtConcurrent namespace provides high-level APIs that make it possible to write multi-threaded programs without using low-level threading (introduced in Qt 4.4.)
  28. 28. QtCore utility classes ● QDate - Date functions ● QDateTime - ● QTime - Clock time functions ● QTimer - Repetitive and single-shot timers ● Date and time functions QPoint - Defines a point in the plane using integer precision
  29. 29. QtCore model classes ● ● ● QAbstractItemModel The abstract interface for item model classes QAbstractListModel Abstract model that can be subclassed to create one-dimensional list models QAbstractTableModelAbstract model that can be subclassed to create table models
  30. 30. Qt Core file/XML classes ● ● ● QtextStream - Convenient interface for reading and writing text QDir - Access to directory structures and their contents QFile - Interface for reading from and writing to files ● QXmlStreamReader - Fast XML streaming API ● QXmlStreamWriter - streaming writer for XML
  31. 31. JSON ● Starting from Qt 5.0 the Qt Core provides a set of classes to enable parsing and generating JSON documents.
  32. 32. Qt GUI and Widgets ● Qt tutorial: – – ● ● Qt UI Qt GUI – ● Qt Widgets – ● Qt Graphics – ●
  33. 33. QApplication and Event loop ● ● QApplication class manages the GUI application's control flow. It's has no graphical presentation but it's used in programs which has an graphical user interface. QApplication manages application's control flow and main setting:
  34. 34. QApplication ● ● ● handles the application's initialization and finalization contains the main event loop where all events from the event sources are processed Setting includes mouse's wheel or double click settings and font setting and setting UI's look&feel style
  35. 35. QApplication ● ● ● provides session management. handles most system-wide and application-wide settings (like application font or style) For any Qt GUI application there is always one QApplication object. – If you don't have GUI then use QCoreApplication instead
  36. 36. QtWidgets ● The QtWidgets module extends QtCore with GUI functionality – ● The core class in QtWidgets module is The QWidget class which is the base class of all UI objects (like QMainWindow or QDialog). Note! When you use Qt Creator or Qt designer to create your UI you save it to XML format – Forms in .ui (XML) file format are compiled during build process into C++ header files by UIC compiler. – If the form is mycomponent.ui then UIC generates ui_mycomponent.h.
  37. 37. Qt GUI before Qt 5 ● ● Prior to Qt 5.0, the Qt GUI module was the monolithic container for all things relating to graphical user interfaces in Qt, and included the Qt widget set, the item views, the graphics view framework and also printing. Starting Qt 5, these classes have been moved to the Qt Widgets module. Printing has been moved to the Qt Print Support module. Please note that these modules can be excluded from a Qt installation.
  38. 38. Qt GUI in Qt 5 ● ● ● QWidget and all derived classes are a core part of Qt 5 on the Desktop. In Qt 5 you can still continue writing apps in exactly the same way as you have been doing with Qt 4.x. Qt5 is mainly source compatibility with Qt 4.x
  39. 39. Qt 5 Widgets
  40. 40. Layout ● ● If some graphical Qt widget should be displayed it need some form of layout to put into the form. All Qt's layouts are derived from the base class, QLayout. – Layouts are geometry managers that fit into the composition hierarchy of a graphical interface.
  41. 41. Qt Layouts ● There are specific layout classes in Qt: – QHBoxLayout, QVBoxLayout – lines up widgets horizontally or vertically – QGridLayout – lays out widgets in grid – QStackedLayout - a stack of widgets
  42. 42. Qt Layouts
  43. 43. QMainWindow ● ● When you want to create a bigger application, which handles many kind of input data and has lot of operation you should use main window to create your application. In the most Qt applications has a single QMainWindow. ● ● It can include many UI components (Qt widgets). It is the parent of all other widgets that are in the main window.
  44. 44. QMainWindow ● It has some common features to all kind of desktop applications: ● ● Menu bar ● Status bar ● Toolbars ● ● A central widget Dock regions It's common practice to derive QMainWindow class to create own main window class.
  45. 45. Qt widgets ● All Qt's widgets are derived from QWidget base class. – QWidget is a base class for all widgets in Qt – creating a new widget you have to subclass the QWidget class. – it has a visual representation on the screen – It is a reusable building block for creating UI – You can form any kind of widget, but also have to implements many methods – internal states, all repainting and size hinting are managed by own widget class
  46. 46. More of QWidget ● ● ● It's a QObject, and thus can have parents, signals, slots, and managed children is a QPaintDevice, the base class of all widgets that can be draw on the screen can handle – signals responsing – event send by other widgets, – mouse, keyboard, other pointer devices – processes etc.
  47. 47. Qt widget hierarchy
  48. 48. QWidget methods ● Some of most important methods of QWidget in example: ● basic things: constructor, sizeHint etc. ● Painting: The paintEvent ● ● Mouse interaction: mousePressEvent, mouseMoveEvent, mouseReleaseEvent. Timing: The QTimer object is connected to the timeout slot
  49. 49. Classes used in UI ● These classes doesn't have graphical presentation but these are commonly used with Qt widgets ● Qt Data types: QPoint and QSize . ● Controller classes: QApplication and QAction. ● Layouts: QHBoxLayout, QVBoxLayout, QGridLayout, etc.
  50. 50. Non-visual classes ● Models: The QAbstractItemModel and its derived classes QAbstractListModel and QAbstractTableModel are part of Qt's Model/View framework, ● ● These models used as base classes for classes that represent data for a corresponding UI components like QListView, QtreeView, or QtableView. Database models: These are used with QTableView for using databases: QSqlTableModel and QSqlRelationalModel.
  51. 51. Qt widgets categories ● ● ● Button widgets (etc.QPushButton, QRadioButton) Input widgets (etc.QLineEdit, QTextEdit, QDateEdit, QSlider ) Display widgets (QLabel, QProgressBar, QPixmap etc).
  52. 52. Qt Widgets categories II ● ● ● Container widgets (QMainWindow, QFrame, QToolBar, QTabWidget ec.) Dialog widgets (QFileDialog, QInputDialog, QErrorMessage etc.) View widget (QListView, QTreeView, QTableView etc.)
  53. 53. GUI classes I ● ● ● ● QAbstractItemModel model classes - abstract interface for item QAbstractItemView - basic functionality for item view classes QAbstractListModel - Abstract model that can be subclassed to create one-dimensional list models QAbstractTableModel -Abstract model that can be subclassed to create table models
  54. 54. GUI classes II ● ● ● ● QAction - Abstract user interface action that can be inserted into widgets QActionEvent - Event that is generated when a QAction is added, removed, or changed QApplication - Manages the GUI application's control flow (event loop) and main settings QBoxLayout - Lines up child widgets horizontally or vertically ● QCheckBox - Checkbox ● QComboBox - Combined button and popup list
  55. 55. Qt GUI classes III ● QCoreApplication applications - Event loop for console Qt ● QDial - Rounded range control ● QDialog - The base class of dialog windows ● QEvent - The base class of all event classes. ● ● ● objects contain event parameters QFileDialog - Dialog that allow users to select files/dirs QFormLayout - Manages forms of input widgets and their associated labels
  56. 56. Qt GUI classes IV ● QGridLayout - Lays out widgets in a grid ● QHBoxLayout - Lines up widgets horizontally ● ● ● ● QImage - Hardware-independent image representation QInputDialog - Simple input dialog QInputEvent - The base class for events that describe user input QIntValidator - Validator for integer within a specified range
  57. 57. Qt Gui classes V ● ● QKeyEvent - Describes a key event QLCDNumber - Displays a number with LCD-look digits ● QLabel - Text or image display ● QLayout - The base class of geometry managers ● QListView - List view onto a model ● QListWidget - Item-based list widget ● QMatrix - 2D transformations of a coordinate system
  58. 58. Qt GUI classes VI ● QMenu ● QMenuBar - ● QMenuItem - an menu item ● QMessageBox - Simple Modal dialog ● QMouseEvent - ● - Menu widget for use in menus menu bar parameters describe a mouse event QPaintDevice - The base class of objects that can be painted
  59. 59. Qt GUI classes VII ● ● ● QPaintEvent - Contains event parameters for paint events QPainter - Performs low-level painting on widgets and other paint devices QPicture - Paint device that records and replays QPainter commands ● QPixmap - Off-screen image representation ● QPushButton - Command button ● QRadioButton - Radio button with a text label
  60. 60. Qt GUI classes VIII ● QScrollArea - Scrolling view onto another widget ● QSpinBox ● ● ● ● - Spin box widget QSplashScreen - Splash screen that can be shown during application startup QSplitter - Implements a splitter widget QStyle - Abstract base class that encapsulates the look and feel of a GUI QStyleFactory - Creates QStyle objects
  61. 61. Qt GUI classes IX ● ● ● ● ● ● QTabBar - Tab bar, e.g. for use in tabbed dialogs QTableView- Default model/view implementation of a table view QTableWidget - Item-based table view with a default model QTextBrowser - Rich text browser QTextDocument - Holds formatted text that can be viewed and edited using a QTextEdit QTextEdit -Widget that is used to edit/display text
  62. 62. Qt GUI classes X ● QToolBar - Movable panel that contains a set of controls ● QToolTip - balloon help ● QTranslator - Internationalization support ● ● ● QTreeView - Default model/view implementation of a tree view QTreeWidget - Tree view that uses a predefined tree model QVBoxLayout - Lines up widgets vertically
  63. 63. Qt GUI programming features ● Signals and slots ● Moc ● Uic ● Qt Events
  64. 64. GUI programming with Qt ● ● Qt's GUI library is very professional level framework This historically the most important reason why Qt has been so successful C++ framework for creating application. – KDE desktop environment has used Qt since 1996 ●
  65. 65. Signals and slots ● In GUI programming, we want objects of any kind to be able to communicate with one another. – if a user clicks a Close button, we probably want the window's close() function to be called.
  66. 66. Signals and Slots ● In Qt, we have an alternative to the callback technique: signals and slots. – It is slightly different way of thinking GUI events and event handling – C++ Macros and a preprocessor makes it feel as if the signal-slot syntax was part of standard C++ – All classes that inherit from QOobject or it's subclasses can contain signals and slots.
  67. 67. Emitting signals ● Signals are emitted when QObject's state is changing – – ● doesn't need to care if there is any Object to handle signals object is like a reusable software component. A signal is emitted when a particular event occurs. – It's possible also to subclass widget and add our own signals to them.
  68. 68. Slot ● A slot is a function that is called in response to a particular signal. – Qt's widgets have many pre-defined slots, but it is also possible to subclass widgets and add your own slots. ● Also QML supports signal-slot mechanism
  69. 69. Q_OBJECT macro ● All classes that contain signals or slots must mention Q_OBJECT macro at the top of their declaration. – must also derive (directly or indirectly) from QObject
  70. 70. QObject::connect ● connect function is a static function of QObject. – It creates connection between two QObject. bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection ) QObject::connect(scrollBar, SIGNAL(valueChanged(int)), label, ● A signal-slot connection is removed when either of the objects involved are destroyed. – ● SLOT(setNum(int))); It's possible to disconnect connection with disconnect() method New signal/slot syntax in Qt5:
  71. 71. Example of signals and slot ● In the next example are used signals and slots mechanism to connect the QSlider's valueChanged() signal to the QLCDNumber's display() slot. – Signal is emitted in event handler method ● MousePressEvent can receive mouse press events for the widget. Other mouse event handlers are mouseMoveEvent and mouseReleaseEvent.
  72. 72. Example cont. void QSlider::mousePressEvent(...) { emit valueChanged( newValue); } Slot is implemented QLCDNumber widget: void QLCDNumber::display(int num) { value = num; } Signal/Slot connection has been defined in the following way: connect( slider, SIGNAL( valueChanged(int) ), lcd, SLOT( display(int) ) );
  73. 73. moc for Qt's C++ extensions ● The meta-object compiler system in Qt: 1.The QObject class acts as a base class. 2.The Q_OBJECT, Q_PROPERTY etc. macros inside the class declaration is used to enable meta-object features (properties, signals, slots...) 3.The Meta-Object Compiler (moc) supplies each QObject subclass with the necessary code to implement meta-object features. ✗ ✗ The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.
  74. 74. Q_OBJECT macro class Counter : public Qobject { Q_OBJECT public: counter() { value = 0; } int value() const { return value; } public slots: void setValue(int value); signals: void valueChanged(int newValue); private: int value; };
  75. 75. Qt's Meta Object Compiler ● Moc provides the flexibility of Java's runtime environments for C++. – maintains C++'s unique performance and scalability advantages. – generates additional C++ code from the header file which can then be compiled by any C++ compiler – If you use qmake to create your makefiles, build rules will be included that call the moc when required.
  76. 76. How's code generation works? I. moc reads C++ source files. II.If class declaration contain the Q_OBJECT macro, it produces another C++ source file which contains the meta object code for those class. III.C++ source files must be linked with the implementation of the class IV.moc is normally automatically called during building the program and programmer don't have to do anything special to use moc.
  77. 77. uic (User Interface Compiler) ● ● ● uic takes a user interface description in XML format (.ui file) and then it can create compiled C++ class Qt's designer and Qt Creator uses this tool when creating UI's Also if you use qmake as a build tool, uic will be invoked automatically for header files (.ui files). – Forms in .ui (XML) file format are compiled during build process into C++ header files by UIC compiler. – If the form is mycomponent.ui then UIC generates ui_mycomponent.h. x
  78. 78. Qt Creator as a UI tool
  79. 79. Qt Events ● ● In Qt, events are objects, derived from the abstract QEvent class, that represent things that have happened either within an application or as a result of outside activity that the application needs to know about. Events can be received and handled by any instance of a QObject subclass, but they are especially relevant to widgets.
  80. 80. Qt Event types ● ● Most events types have special classes, notably QResizeEvent, QPaintEvent, QMouseEvent, QKeyEvent, and QCloseEvent. Each class subclasses QEvent and adds event-specific functions. For example, QResizeEvent adds size() and oldSize() to enable widgets to discover how their dimensions have been changed.
  81. 81. Qt Event ● QMouseEvent class contains parameters that describe a mouse event (like x,y position or keyboard modifiers or ) void MyCheckBox::mousePressEvent(QMouseEvent *event) {     if (event­>button() == Qt::LeftButton) {         // handle left mouse button here     } else {         // pass on other buttons to base class         QCheckBox::mousePressEvent(event);     } }
  82. 82. Event handlers void QWidget::mousePressEvent(QMouseEvent * event)  [virtual protected] – This event handler, for event event, can be reimplemented in a subclass to receive mouse press events for the widget. void QWidget::mouseReleaseEvent(QMouseEvent * event)  [virtual protected] – ● This event handler can be reimplemented in a subclass to receive mouse release events Valid event types in Qt 5:
  83. 83. The model/view architecture ● ● ● The model communicates with a source of data, providing an interface for the other components in the architecture. The view obtains model indexes from the model, which are references to data items a delegate renders the items of data. – When an item is edited, the delegate communicates with the model directly using model indexes.
  84. 84. MVC architecture support MVC implementation in Qt 4: The model/view architecture – easy to distinguish UI elements from the data – requires underlaying a data model ● The data is fed back to the model from the UI component ●
  85. 85. Qt Model's Views ● Possible Views are: – QListView displays a list of items, – QTableView displays data from a model in a table, – QTreeView shows model items of data in a hierarchical list. – Each of these classes is based on the QAbstractItemView abstract base class
  86. 86. Item Views classes ● Item view classes are similar than item view classes provided by previous versions of Qt. – ● These are suitable for situations, where we need to use only relatively few UI items. Qt's convenience item view classes includes: – – QTableWidget, – ● QListWidget, QTreeWidget These classes stores their data in "items" – QTableWidget contains QTableWidgetItems etc.
  87. 87. QTableView ● ● Qt's views (like QTableView, ) is used with a data model, which can be a custom model or one of Qt's predefined models. If using table view model can be inherited from QAbstractTableModel. – When subclassing QAbstractTableModel, you must implement rowCount(), columnCount(), and data(). – Default implementations of the index() and parent() functions are provided by QAbstractTableModel.
  88. 88. Model classes ● ● QAbstractItemModel is interface to data and can handle views that represent data in the form of tables, lists, and trees. models for list and table-like data structures, the QAbstractListModel and QAbstractTableModel provides default implementations of common functions
  89. 89. File/Database models ● QStringListModel, ● QStandardItemModel, ● QFileSystemModel, – QFileSystemModel class provides functions for renaming and removing files/ directories, and for creating new directories in the local filesystem ● QSqlQueryModel, ● QSqlTableModel or QSqlRelationalTableModel – if the data is in a relational database, we can combine a QTableView with a QSqlTableModel
  90. 90. GraphicsView ● Graphics View Framework was developed for Qt 4.2 and it's efficient for managing and interacting 2D graphical object in the graphical surface. – Has surface for managing and interacting with a large number of 2D graphical items efficiently – Provides a view widget for visualizing the items, with support for zooming and rotation. – Graphics View provides an item-based approach to graphical programming, much like M/V classes QTableView, QTreeView and
  91. 91. Graphics View ● QGraphicsView – The base class for Graphics View framework – most applications are built around a twodimensional canvas – a feeling of a custom widget without actually creating a custom widget.
  92. 92. Graphics View basics ● Three basic components: view, scene,item ● These components are – QGraphicsView, shows the contents of a scene – QGraphicsScene ● – manages collection of widgets, the propagation of events and item's state like selection or focus. Each graphical item has subclass of QGraphicsItem (single item/group of items)
  93. 93. QGraphicsItem ● QGraphicsItem supports the following features: – Basic Mouse events, and mouse hover and wheel events. – Key events – Drag and drop – Grouping (QGraphicsItemGroup) of graphical items – Transformations like transform, rotating, scaling – Collision detection
  94. 94. Collision detection – QGraphicsItem supports also collision detection ● ● – QGraphicsItem's collision detection uses boundingRect() method ● – Detection collision is one of the base demand in games QGraphicsItem supports collision detection through the shape() function, and collidesWith It defines the outer bounds of the item as a rectangle The more fine grained collision algorithm is based on calling shape which returns an accurate outline of the item's shape
  95. 95. Collision intersection ● ● You can specify how items and shapes collide bool QGraphicsItem::collidesWithItem ( const QGraphicsItem * other, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) – Qt::ContainsItemShape – Qt::IntersectsItemShape (default mode) ● other collides with this item if it either intersects, contains, or is contained by this item's shape – Qt::ContainsItemBoundingRect – Qt::IntersectsItemBoundingRect
  96. 96. Localization in Qt ● ● ● increasingly important in the global software market In localization Qt programmers task is relatively easy to do In the source code put Qstring object into tr() function – ● QLabel mystr(tr ("Hello World !")); Function can be used even if it's not need to translate right now
  97. 97. Translation in a program // Setting Locales and translators for this applications // Now use tr() function in every String QString locale = QLocale::system().name(); QTranslator translator; translator.load(QString("locales_") + locale); // Testing with finish locale setting // translator.load(QString("locales_fi")); app.installTranslator(&translator);
  98. 98. tr() function and lupdate ● QObject:: tr() Returns the translation of the text or original copy, if a translation does not exist lupdate – ● The lupdate tool is used to synchronize source code and translations. lrelease – ● – is used to create run-time translation files for use by the released application.
  99. 99. TS files ● TS files are XML files – You can edit these files by hand or using Qt Linquist tool <TS version="2.0" language="fi_FI"> <context> <name>QLabel</name> <message> <source>Hello Colourful QT!</source> <translation type="unfinished">Moi Varikas Qt</translation> </message> </context>
  100. 100. Qt Linquist ● ● Can use Qt Linquist translation program can be used for editing translation files QM files can be created as follows lrelease is a command line tool that produces QM files (binary format) out of TS files – Qt Linquist programs (File / Release) –
  101. 101. Qt Stylesheets You can use CSS like language ● Basic process – Create a stylesheet file (.qss file) ● Should be in Qt resource file also – Insert stylesheet into the application ●
  102. 102. Setting Stylesheet Using Qt stylesheet in the code is easy ● Use application wide settings if possible because it's easier to modify afterwards ● QFile file(":/qstyle.qss"); if( == true) { // open file and set it to // the style of the Qt application QString styleSheet(file.readAll());
  103. 103. qss stylesheet language ● Example of defining Qt stylesheet file in .qss file: QLabel { font-weight: bold; font-size: 15px; border: 2px solid green; border-radius: 4px; QLabel:enabled { color: red } QLabel:hover:enabled { color: black } /* pseudo classes CSS like */ padding: 2px; }
  104. 104. Defining styles ● ● ● You can reference component directly from QSS using object's class#name like (QDial#ageDial) You can define stylesheet directly in source code into component using method QWidget::setStyleSheet() button->setStyleSheet( "QPushButton {color:white; background:rgb(255,255,0); border-radius:10px; font:bold 16px; font-family:"Arial";}”);
  105. 105. Dynamic effects with qss ● :focus input focus ● :hover mouse is moving over the component ● :pressed clicked ● :checked,:unchecked ● ● :open, :close expanded or not :enabled :disabled, :on, :off . You can create realtime effects without modified the Qt code
  106. 106. Qt 5 Resources ● Qt 5 project: ● Tools: ● Docs: ● Qt Commercial: ● ● ● KDE tutorial: Qt 5 features: Qt Location: