Qt Framework - Magnifier 3D

Download Report

Transcript Qt Framework - Magnifier 3D

Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
Programming with Qt
- Containers (Tulips)
- Widgets
- XML
- Interview (MVC)
- Webkit
- Canvas
- Database
- Networking
- 2D/3D graphics
- Graphics View
- Thread/IPC
- Phonon
- Multimedia
- OpenGL
- QML and JavaScript
- Android and iOS
Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
Qt History
• Pronounce “Cute” or Qt
• Cross platform application development
framework
• User experience across hardware platforms
• It goes beyond GUI (database access, xml
parser, web, …)
• It can bind to any language and can be
written in C++, python, C#, Ruby, Ada, Pascal,
PHP, Perl, and Java.
Qt History
•
•
•
•
•
•
•
Qt Was initially developed by two persons, Haavard Nord
(CEO), and Eirik Chambe (President) in early 90.
Both graduated from Norwegian Institute of Technology
in Computer Science and formed Throlltech Inc. in 1995.
Qt 4 was published in Summer 2005 (major milestone)
In 2008 acquired by Nokia (Finnish company)
In 2012, acquired by Digia (Finnish company)
3 licenses (GPL/GNU GPL/Commercial)
The commercial you don’t have to share the code in
open source
Qt History
• Traditional C++, but later (4.7) with Qt Quick and
QML with JavaScript where it is ideal for
tablet/smartphone
• Leverage with C++ , less learning curve
• It is high quality, mature, free, excellent support
for localization, support 32/64 bit computing
• Presently Qt 5.2 and Qwt 6.1 (latest version)
• Rich set of Widgets (1000+), Qwt (125+) classes
• Very Good Documentation, help, and examples
Qt Project: http://www.qt-project.org
Digia Site:
http://qt.digia.com
Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
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, …
Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
Benefit
a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Cross platform GUI framework (develop on one machine and port it to any
other machine)
Rich API class w/ C++ library, along an IDE with different tools to support
Superior Graphics performance with power of C++ and Qt Object Model
A very powerful mechanism for seamless object communication called
signal sand slots (callback system)
Query able and designable object properties
Contextual string translation for internationalization
Sophisticated interval driven timers that make it possible to elegantly
integrate many tasks to an event driven GUI
Hierarchical and query able object trees that organize object in a natural
way
Guarded pointers (QPointer) that are automatically set to 0 when the
referenced object get destroyed
A dynamic cast that works across library boundary
Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
Tools








Qt Creator : Cross platform IDE
Qt Designer: GUI layout and forms builder
Qt Linguest: Internationalization toolset
Qt Assist:
Customizable documentation reader
Qt Qmake: 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
Qt Modular Class Library
Building Qt Application (Qmake)
Qmake : Creates Qt Project file (.pro) , can also be created
manually.:
$Qmake –project (generates “hello.pro”)
$qmake hello.pro(generates “Makefile”)
$make (use nmakeif running on Windows)
Qmake : Uses the .pro file as input produces platform specific
Makefiles)
Generates make rules to invoke moc for project header files
containing Q-Object
Make: Compiles the program for the current platform
Executes also moc, uic and rcc
Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
Qt Architecture
Qt SDK
The Qt class library encompasses all the functions needed build robust,
high end applications, and they can be separate into several modules:
-
Core Framework
GUI Framework
SQL Framework
XML Framework
Networking Framework
OpenGL Framework
Multimedia Framework
WebKit Framework
Phonon Framework
- OpenGL framework
-2D with Painter framework
- Scene Graph framework
- SVG Framework
Qt Class Library
QtCore: File I/O, event and object handling, multi-threading and
concurrency, plugins, setting management signals and slots interobject communications mechanism
QtGui: Set of customizable widgets, 2D graphics canvas and
OpenGL® integration, powerful font and layout engine
style engine and widget style sheets, anti-aliasing, vector
deformation, and SVG support, advanced graphics effects
support for ARGB top-level widgets
Qt Framework
•
•
•
•
•
•
•
Qt History
Who uses Qt
Benefits
Tools and components
SDK
Core Internals
Programming with Qt
Core Internals






Object Model
Meta Object System
Property System
Signal and Slots
State Machine Framework
Timers
Core Internals





Object Model
Meta Object System
Property System
Signal and Slots
Event System
Object Model
Qt’s Object Model (QObject)
• GUI programming is a domain that requires
both runtime efficiency and a high level of
flexibility. Although C++ object model is
efficient at runtime but its static nature is
inefficient in graphical domain. Qt provides
this, by combining the speed of C++ with the
flexibility of the Qt Object Model.
• Meta-Object system : Allows runtime
introspection, manipulation and invocation of
properties and methods in the object.
Core Internals





Object Model
Meta Object System
Property System
Signal and Slots
Event System
Meta Object System
• The QMetaObject class contains metainformation about Qt objects.
• Classes must be predefined with Qt “moc”
• Class declarations must include Q_OBJECT
macro
• Responsible for the signals/slots inter-object
communication mechanism, runtime type
information, and the Qt property system
• Qmake takes care of this automatically
Core Internals






Object Model
Meta Object System
Property System
Signal and Slots
State Machine Framework
Timers
Property Systems




Provides a sophisticated property system
Does not rely on non-standard compiler features
like __property or [property].
Works with any standard C++ compiler on every platform Qt supports.
To declare a property, use the Q_PROPERTY() macro in a class that
inherits QObject.
Q_PROPERTY(type name
READ getFunction
[WRITE setFunction]
[RESET resetFunction]
[NOTIFY notifySignal]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool]
[CONSTANT]
[FINAL])
Property Systems
Keep track of a priority value. priority(name of property)
and its type will be enumeration type named Priority
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(Priority priority READ,
priority WRITE,
setPriority NOTIFY priorityChanged)
Q_ENUMS(Priority)
Core Internals





Object Model
Meta Object System
Property System
Signal and Slots
Event System
Callbacks
•
•
Traditional callbacks (a pointer to a function)
Problems: not type safe: does the caller use the
correct arguments?
•
•
•
•
•
Observer Pattern
Called when appropriate (event notification, …)
Many to many relationship
Loose coupling between signals and slots
Less generic: callback strongly coupled to processing
function
Processing function must which callback to call.
•
Inter-Object Communication
The user clicks the OK button
-What happens?
How do we react to the button press?
Answer:
-Signals and slots
Type safe callbacks
Signals are emitted by objects
Slots are function that react to signals
Slots are regular method calls
Handled entirely by Qt’s meta object system
Signals and Slots
• Signal and Slots run at the run time
• Use the “connect” method to join signal and slots
•
connect( slider,
SIGNAL( valueChanged( double ) ) ,
plot,
SLOT(setIntervalTime(double)));
Same type, and number of
parameters
• Predefined signals and slots by classes
• Otherwise you have to write it depends of what you need
• In the header file:
•
•
Q_SIGNALS(signals):
Q_SLOTS(slots):
• Parsed by Qt’s Meta Object Compiler (moc)
Signals
• A signal is a way to inform a possible observer something
of interest has happened inside the observed class
• A PushButton clicked (an asynchronous service) where
the value of Slider is changing.
• Signals are member functions that automatically
implements in the meta-object
• Only the function declaration is provided by the
developer
• Signal is sent, or emitted using the keyword emit ( i.e.
Emit someSignal(“Hello”) )
Slots
• Regular class member methods
• Should be declared as void
• Slots can return a value when called as a
method
• Return values are ignored when invoked from
a signal
• May include in access specifier(pubic, private,
..)
• A slot is a function that is to be executed
when a signal has been emitted: (i.e. when
QPushButton is pressed, Close a Qdialog)
Core Internals





Object Model
Meta Object System
Property System
Signal and Slots
Event System
Event Systems
•
Events are objects, derived from abstract QEvent class,
usually receives from window system and dispatch it to
widgets.
•
When an event occurs, Qt Creates an event object (an
instance of the QEvent), and therefore delivers to an
instance of QObject.
Based on the type of event delivered, response will be send if
the event was accepted or ignored
• Such as QMouseEvent and QKeyEvent, come from the
window system;
How Events are Delivered
When an event occurs,
• Qt Creates an event object (an instance of the
QEvent),
• Delivers it to a particular instance of QObject
Based on the type of event delivered, response will be
send if the event was accepted or ignored
• Such as QMouseEvent and QKeyEvent, come from
the window system;
How Events are Delivered
Event Types
Most events types have special classes, notably
•
•
•
•
•
QResizeEvent,
QPaintEvent,
QMouseEvent,
QKeyEvent,
QCloseEvent.
Each class subclasses QEvent and adds event-specific functions.
For example,
QResizeEvent adds size()
Hello World
Hello World
Concepts in Qt Widgets
o
o
o
o
o
Application Main Window
Desktop Integration
Dialog Windows
Layout Management
Model/View Programming
Application Main Window
Classes for managing main windows and associated UI
components:
QMainWindow: is the central class around which applications can
be built on top level UI.
QDockWidget: provides a widget that can be used to create
detachable tool palettes or helper windows.
QToolBar: provides a generic toolbar widget that can hold a
number of different action-related widgets, such as buttons,
drop-down menus, combo boxes, and spin boxes.
Desktop Integration
These classes enable developers to take advantage of native services
while still using a cross-platform API.
QDesktopServices: provides an interface to services offered by the
user's desktop environment (such as openUrl() function).
QSystemTrayIcon: docks or panels with system trays in which
applications can install icons, to display status information, either by
updating the icon itself or by showing information in "balloon
messages".
QDesktopWidget: to monitor the positions of widgets and notify
applications about changes to the way the desktop is split over the
available screens. This enables applications to implement policies for
positioning new windows so that, for example, they do not distract a
user who is working on a specific task.
Dialogs
ColorDialog
Dialog component for choosing a
color.
FileDialog
Dialog component for choosing files
from a local file system.
FontDialog
Dialog component for choosing a font.
MessageDialog
Dialog component for displaying
popup messages.
Layout Classes
•
•
•
•
QHBoxLayout: Lines up widgets horizontally.
QVBoxLayout: Lines up widgets vertically.
QGridLayout: Lays out widgets in a grid.
QStackedWidget: Stack of widgets where only one widget is
visible at a time
• QStackedLayout: Stack of widgets where only one widget is
visible at a time
• QFormLayout: Manages forms of input widgets and their
associated labels
• And many more …
Qt Strings
•
•
•
•
Built-in Unicode support,
Useful methods (i.e. trimmed(), split())
Cheap copying (implicit sharing)
Believe it or not, they can actually contain embedded ‘\0’ characters
…
• Concatenation and formatting:
Qstring first = Joe”;
Qstring last = “Doe”;
Qstring fullname = first + “ “+ last;
Qstring fullname2 = Qstring(“%1 %2).arg(first).arg(last));
Translation:
Qstring translatedSend = tr(“Send”);
Qt Strings
Splitting/Joining on a delimiter character
QString numbers = “1, 2,3,4,45,6,23”;
QStringList nums = numbers.split(‘,’);
int sum=0;
foreach(Qstring num, numberList)
Sum +=num.toInt();
Removing leading or trailing whitespace:
QString name = “ Joe Doe”;
QString trimedName = name.trimmed();
Model/View Programming (1)
Qt uses a model/view architecture to manage
the relationship between data and the way it
is presented to the user.
MVC consists of 3 kinds of objects, the “Model”
is the application object, the “View” is its screen
presentation, and the “Controller” defines the
way the user interface reacts to user input.
You have data, and you put part of data into model, View renders
and displays the data.
Model/View Programming (3)
Model/View Programming (2)
Add headers
Add in private
section
Model/View Programming (4)
Qt Tulips
•
•
•
•
•
•
•
Container objects STL-like collection classes
Sequential (lists, vectors, queues, and stacks)
and Associative (Sets, hashes, maps)
Use implicit sharing (i.e. copy on write) thread
safe
Supports both STL and Java Style iterators
Wrapper STL like collection classes, lighter,
safer than STL classes
Efficient use for objects referenced by value
Includes important algorithm (i.e. copy, sort,
find, count, remove, fill, comparison,)
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 controlable out formatting
• XSLT support
Qt Webkit
• Based on the Open Source Webkit engine
• Webkit is basis for Apple's Safari browser, and numerous other
browsers (i.e. Safari, Chrome, and iPhone, http://webkit.org)
• Apple originally based Webkit on KHTML/KJS from KDE (done with
QT)
• QWebkit is web rendering engine, JavaScript engine, and provides
classes for integrating Qt and web content to create hybrid
applications
• Capabilities can do HTML4 and parts of HTML5 (2D canvas,
Audio/Video playback, off-line apps, web workers, storage and SQL
database)
• In addition, CCS1 and CCS2 and part of CSS3 (Backgrounds and
borders, fonts, 2D/3D transformations, transitions and animations)
• It is done via “QWebView”, “QWebPage”, and “QWebFrame” classes
• The DOM (Document Object Model) is accessible through the
“QWebElement” class.
Qt Phonon
• Single easy to use API for playback
• Provides possibility to play/synchronize multiple
sound/video streams
• Will use native back-end format support
• DirectShow
• GStreamer
• QuickTime
• MVF (Symbian)
• Plan to add more video and other authoring support
in future
Qt Canvas
• Alternative to QPainter (but may still use QPainter).
• QCanvas where you put graphical objects like polygons, texts,
pixmaps.
• It also provides additional items by subclassing QCanvasItem
or one of its more specialized subclasses.
• Supports huge numbers of figures.
• Supports checking for overlap (collision) of figures.
• Supports checking for collision with a QPoint.
• Optimized to reduce flicker, even with lots of figures.
• QCanvasView is used to display and CanvasPolygonalItem for
manipulating objects
Qt OpenGL
•
•
•
•
•
QGLWidget is the class supporting the OpenGL in Qt
A widget for rendering OpenGL graphics.
More than 250 functions to produce 3D scene
You can run 2D as well as 3D, and it is cross platform
QGLWidget provides functionality for displaying OpenGL
graphics integrated into a Qt application.
• The QGLWidget creates a GL overlay context in addition to the
normal context if overlays are supported by the underlying
system.
• Improves drastically performance on threading with “buffer
swapping”, “Texture uploading”, as well as “QPainter”
Qt GraphicsView
• Painting is primitive graphics (QPainting, i.e. Photoshop).
• Problem: low level abstraction, and low reuse
• Drawing is structured graphics, with high level of abstraction
and high reuse (QGraphicsView). Illustrator is an example.
• Q is a structured graphics, Object Oriented, can do
composition (like a house, square shape and we can make it
rectangle, transform it, and …)and we can move them,
transform them, stacked them , and … like KDE desktop it is
done completely by QGraphicsView
• QGraphicsView is based on Model/View architecture
• It efficiently manage a large number of items, event
propagation, resolution independent, and animation support
Qt Graphics View
• The Graphics View Frameworks is a scene based approach to
graphics
• QGraphicsItem, QGraphicsScene, and QGraphicsView
• You have more control over the widget shape and overlapping
• This will support more items and much more flexible to move
around
• The QGraphicsScene class contains all items and acts as an
interface between the view and the items
• It is based on BSP (Binary Space Partitioning trees store
items in a tree, depending on their location in space) and
therefore extremely efficient in terms of performance.
Qt Multimedia
• Multimedia support in Qt is provided by the Qt Multimedia
module
• Provides a rich feature set that enables you to easily take
advantage of a platforms multimedia capabilities and H/W.
• This ranges from the playback and recording of audio and
video content to the use of available devices like cameras and
radios.
• There are components for Audio, Video, Camera, as well as
Radio
• Some of the features:
• Access raw radio, play and record, compress, decode and
access audio and video frames.
Qt Networking
• Classes for writing TCP/IP clients and servers
• Provides access to the web without any connections to a user
interface and handles requests/replies, cache web pages, keep
track of cookies, use proxies, act as a protocol translator.
• Browsing the web uses the HTTP, TCP/IP, FTP, SMTP, POP and
IMAP protocols.
• Supports accessing TCP and UDP directly at socket level
• 2 TCP classes in Qt: QTcp(Udp)Socket and QTcp(Udp)Server.
• The QtWebKit classes uses the “QNetworkAccessManager” to
access the net.
Qt Networking
• QNetworkAccessManager to handle network communication.
• TCP (Transmission Control Protocol) is a low-level network
protocol used by most Internet protocols, including HTTP and
FTP, for data transfer. It is a reliable, stream-oriented,
connection-oriented transport protocol. It is particularly well
suited to the continuous transmission of data.
• UDP (User Datagram Protocol) is a lightweight, unreliable,
datagram-oriented, connectionless protocol. It can be used
when reliability isn't important. For example, a server that
reports the time of day could choose UDP. If a datagram with
the time of day is lost, the client can simply make another
request.
Qt Networking
Qt QThread(IPC)
• What a thread has:
Its own stack pointer,
instruction(program counter),
processor registers and
execution state
Instead of starting in main()
QThreads begin executing
in run(). By default, run()
starts the event loop by calling exec
It access to shared
resources (shared memory,
wait conditions, mutually
exclusive data blocks and
semaphores) in app’s
address space
Qt QThread(IPC)
Execution ends when
you return from run()
method
By default, by calling
the exec(), run() starts
the event loop
Qt QThread(IPC)
• QThread will notify you via a signal when the thread
is started(),finished(), and terminated(),
• Use isFinished() and isRunning() to query the state of
the thread,
• Use wait() to block until the thread has finished exec.
Qt QThread(IPC)
Qt QThread(IPC)
• The QThread class provides platform-independent threads.
• Qt supports multi-threading and encapsulates threads using
QThread class.
• Most QObjects are thread safe and re-entrant, and can
communicate across threads.
• Qt can only can have only one GUI thread (QApplication)
• Any widgets inherited from QWidget are not thread safe, but
we can use signal and make threads to communicate between
the back-end application to the front.
• QThreads begin executing in run() method.
• By default,run() starts the event loop by calling exec() and runs
a Qt event loop inside the thread.
QThread
• Another way to make code run in a separate thread, is to
subclass QThread and re-implement run().
• QMutex provides access serialization between threads. The
purpose of QMutex is to protect an object, data structure or
section of code so that only one thread can access it at a time
(similar to the Java synchronized keyword). It is usually best to
use a mutex with a QMutexLockersince this makes it easy to
ensure that locking/unlocking are performed onsistently.
• QSemaphore is a generalization of a mutex. While a mutex can
only be locked once, it's possible to acquire a semaphore
multiple times. Semaphores are typically used to protect a
certain number of identical resources.
QThread
• QtConcurrent namespace provides high-level APIs that make it
possible to write multi-threaded programs without using lowlevel threading primitives.
• One important class in this namespace is QThreadPool, a class
that manages a pool of threads.
• Every Qt application has a QThreadPool::globalInstance() with
a suggested maximum thread count that defaults, on most
systems, to the number of cores.
• Using QtConcurrent's functional map/filter/reduce algorithms,
which apply functions in parallel to each item in a container,
you can write a program that automatically takes advantage of
the system's multiple cores by distributing the processing
across the threads managed by the thread pool.
Qt Resources
•
•
•
•
File embedded in Qt applications and libraries
Accessed with Qt file objects and methods
Dynamic file name space
Usually starts with “:” path and file ending with .qrc and
qmake will handle that automatically for you
• Benefit: deploy the executable with resources
Qt Internationalization
• Internationalization/Localization (i8
• Multi-byte character sets
• Translation methods
• Unicode support
• Using QString (support Unicode), and QChar(conversion to
local character sets)
• Context sensitive resources file aliases
• Translation tools (string extraction, translation editor)
• Wrap all the string in macro “tr” and save in .ts file
• (i.e. QLabel label (“tr(“username”))
• Using Qt Linguist (graphical tool table based translation editor)
Qt Android
 Started to deploy on Qt 5.x
 Originally the Light house project
 Two additional tools;
1.
Necessitas (Lighthouse project deploy to Android)
2.
Ministro(deployment library to the consumers)
 You need Android SDK and NDK installed on your
machine
 Setup the path in QtCreator
 To deploy use the Ministro (deployment service)
QML and JavaScript
• Qt Quick with QML and you can use JavaScript for engine
along C++
• Started to be released since late 2009 (Qt 4.7)
• Nokia focused on that for the Symbian/Meego phone and
future smartphone development
• Support on QtCreator
• JavaScript-based declarative Components
• Sub classing QDeclerativeItem