SlideShare ist ein Scribd-Unternehmen logo
1 von 98
. An Introduction to Qt and Workshop Qt in Education
http://www.pelagicore.com/documents/2011-Apr-QtWorkshop.odp © 2011 Nokia Corporation and its Subsidiary(-ies). The enclosed Qt Materials are provided under the Creative Commons  Attribution-Share Alike 2.5 License Agreement.  The full license text is available here:  http://creativecommons.org/licenses/by-sa/2.5/legalcode . Nokia, Qt and the Nokia and Qt logos are the registered trademarks  of Nokia Corporation in Finland and other countries worldwide.
The Presenter ,[object Object]
Thesis work within embedded Linux, open source and design
What is Qt? ,[object Object],“ Qt is a cross platform development framework written in C++.”
What is Qt? ,[object Object],QtCore Phonon QtXmlPatterns QtXml QtWebKit QtSvg QtSql QtScript QtOpenVG QtOpenGL QtNetwork QtMultimedia QtGui
What is Qt? ,[object Object]
All code is still plain C++ foreach (int value, intList) { … } QObject *o = new QPushButton; o->metaObject()->className(); // returns ”QPushButton” connect(button, SIGNAL(clicked()), window, SLOT(close()));
Desktop target platforms ,[object Object]
Mac OS X
Linux/Unix X11
Embedded target platforms ,[object Object]
Symbian
Maemo
Embedded Linux ,[object Object]
Community target platforms ,[object Object],http://sourceforge.net/p/necessitas/home/ ,[object Object]
Hello World
Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
The QObject ,[object Object]
They are placed in a hierarchy of  QObject  instances
They can have connections to other  QObject  instances
Example: does it make sense to copy a widget at run-time? “ QObject instances are individuals!”
Meta data ,[object Object]
Every  QObject  has a  meta object
The meta object knows about ,[object Object]
inheritance ( QObject::inherits )
properties
signals and slots
general information ( QObject::classInfo )
Memory Management ,[object Object]
When a parent object is deleted, it deletes its children QObject *parent = new QObject(); QObject *child1 = new QObject(parent); QObject *child2 = new QObject(parent); QObject *child1_1 = new QObject(child1); QObject *child1_2 = new QObject(child1); delete parent;
Memory Management ,[object Object],QDialog *parent = new QDialog(); QGroupBox *box = new QGroupBox(parent); QPushButton *button = new QPushButton(parent); QRadioButton *option1 = new QRadioButton(box); QRadioButton *option2 = new QRadioButton(box); delete parent;
Usage Patterns ,[object Object]
Allocate parent on the stack void Widget::showDialog() { Dialog dialog; if (dialog.exec() == QDialog::Accepted) { ... } } Dialog::Dialog(QWidget *parent) : QDialog(parent) { QGroupBox *box = QGroupBox(this); QPushButton *button = QPushButton(this); QRadioButton *option1 = QRadioButton(box); QRadioButton *option2 = QRadioButton(box); ...
Heap ,[object Object]
Heap memory must be explicitly freed using  delete  to avoid memory leaks.
Objects allocated on the heap can live for as long as they are needed. new delete Construction Destruction
Stack ,[object Object]
Stack variables are automatically destructed when they go out of scope.
Objects allocated on the stack are always destructed when they go out of scope. int a } Construction Destruction
Stack and Heap ,[object Object],int main(int argc, char **argv) { QApplication a(argc, argv); MyMainWindow w; w.show(); return a.exec(); } MyMainWindow::MyMainWindow(... { new QLabel(this); new ... } MyMainWindow QApplication
Signals and Slots ,[object Object]
What makes Qt tick
Signals and Slots in Action emit clicked();
Signals and Slots in Action private slots: void on_addButton_clicked(); void on_deleteButton_clicked(); connect(clearButton,SIGNAL(clicked()),listWidget,SLOT(clear())); connect(addButton,SIGNAL(clicked()),this,SLOT(...)); 2x clear();
Signals and Slots in Action { ... emit clicked(); ... } { ... emit clicked(); ... } { ... emit clicked(); ... } { QString newText =  QInputDialog::getText(this,  &quot;Enter text&quot;, &quot;Text:&quot;); if( !newText.isEmpty() ) ui->listWidget->addItem(newText); } { foreach (QListWidgetItem *item,  ui->listWidget->selectedItems()) { delete item; } } clear();
What is a slot? ,[object Object]
A slot can return values, but not through connections
Any number of signals can be connected to a slot
It is implemented as an ordinary method
It can be called as an ordinary method public slots: void aPublicSlot(); protected slots: void aProtectedSlot(); private slots: void aPrivateSlot(); connect(src, SIGNAL(sig()), dest, SLOT(slt()));
What is a signal? ,[object Object]
A signal always returns void
A signal must not be implemented ,[object Object],[object Object]
Usually results in a direct call, but can be passed as events between threads, or even over sockets (using 3 rd  party classes)
The slots are activated in arbitrary order
A signal is emitted using the emit keyword signals: void aSignal(); emit aSignal();
Making the connection QObject::connect( src, SIGNAL( signature ), dest, SLOT( signature ) ); <function name> ( <arg type>... ) clicked() toggled(bool) setText(QString) textChanged(QString) rangeChanged(int,int) setTitle(QString text) setValue(42) A signature consists of the function name  and argument types. No variable names,  nor values are allowed. Custom types reduces reusability. setItem(ItemClass)
Making the connection ,[object Object],Signals rangeChanged(int,int) rangeChanged(int,int) rangeChanged(int,int) valueChanged(int) valueChanged(int) valueChanged(int) textChanged(QString) clicked() clicked() Slots setRange(int,int) setValue(int) updateDialog() setRange(int,int) setValue(int) updateDialog() setValue(int) setValue(int) updateDialog()
Automatic Connections ,[object Object]
Triggered by calling  QMetaObject::connectSlotsByName
Think about reuse when naming ,[object Object],on_  object name   _  signal name   (  signal parameters   ) on_addButton_clicked(); on_deleteButton_clicked(); on_listWidget_currentItemChanged(QListWidgetItem*,QListWidgetItem*)
Much more... ,[object Object],http://qt.nokia.com/qtquick/
Goal of the day ,[object Object]
Dialogs
Menus, toolbars, statusbars
Basic file management Open, Save and Save As We will run out of time!
Goal of the day
Creating a project ,[object Object]
Use the  QtCore  and  QtGui  modules
Base the skeleton project on a  QMainWindow
Creating a project ,[object Object]
mainwindow.ui  – the user  interface of the main window
mainwindow.h/cpp  – the class  declaration and implementation  of the main window
main.cpp  – the main function,  getting everything initialized  and running
The plan ,[object Object]
Features will be added to the application, while maintaining a functioning application through-out the process
This is how most software is being built  in real life!
Starting with the user interface ,[object Object]
Starting with the user interface ,[object Object]
Starting with the user interface ,[object Object],You have to  deselect and reselect the central widget to see these properties after  you have applied  the layout
Adding actions ,[object Object]
For each of these user actions, a  QAction  object will be created
Why QAction ,[object Object]
Do not forget tooltips, statusbar tips, etc. Ctrl+S Action
Why QAction ,[object Object]
Commonly used properties are ,[object Object]
icon  – icon to be used everywhere
shortcut  – shortcut
checkable / checked  – if the action is checkable and the current check status
toolTip / statusTip  – tips text for tool tips (hover and wait) and status bar tips (hover, no wait)
Why QAction QAction *action = new QAction( parent ); action->setText(&quot;text&quot;); action->setIcon(QIcon(&quot;:/icons/icon.png&quot;)); action->setShortcut(QKeySequence(&quot;Ctrl+G&quot;)); action->setData(myDataQVariant); Setting properties for text, icon and  keyboard short-cut Creating a new action A QVariant can be associated with each action, to carry data associated with the given operation
Why QAction ,[object Object]
Tools – Form Editor –  Views – Action Editor ,[object Object]

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QMLAlan Uthoff
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesICS
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVICS
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4ICS
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt InternationalizationICS
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical PresentationDaniel Rocha
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickICS
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphICS
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key conceptsICS
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
Introduction to Qt Creator
Introduction to Qt CreatorIntroduction to Qt Creator
Introduction to Qt CreatorQt
 

Was ist angesagt? (20)

Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
Qt Qml
Qt QmlQt Qml
Qt Qml
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt Quick
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene Graph
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key concepts
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
Introduction to Qt Creator
Introduction to Qt CreatorIntroduction to Qt Creator
Introduction to Qt Creator
 

Andere mochten auch

Witekio Qt and Android
Witekio Qt and AndroidWitekio Qt and Android
Witekio Qt and AndroidWitekio
 
Tizen Native Application Development with C/C++
Tizen Native Application Development with C/C++Tizen Native Application Development with C/C++
Tizen Native Application Development with C/C++Gilang Mentari Hamidy
 
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014Verold
 
Starting Development for Nokia N9
Starting Development for Nokia N9Starting Development for Nokia N9
Starting Development for Nokia N9tpyssysa
 
Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Frameworkaccount inactive
 
Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009Nokia
 
Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.jsJames Williams
 
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQtPyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt덕규 임
 
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...Andreas Jakl
 
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...Marius Bugge Monsen
 
서버 개발자가 되기 전에 알았으면 좋았을 것들
서버 개발자가 되기 전에 알았으면 좋았을 것들서버 개발자가 되기 전에 알았으면 좋았을 것들
서버 개발자가 되기 전에 알았으면 좋았을 것들raccoony
 
금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014Seung-June Lee
 
WebGL and Three.js
WebGL and Three.jsWebGL and Three.js
WebGL and Three.jsyomotsu
 
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...vtunotesbysree
 

Andere mochten auch (16)

Cross Platform Qt
Cross Platform QtCross Platform Qt
Cross Platform Qt
 
Witekio Qt and Android
Witekio Qt and AndroidWitekio Qt and Android
Witekio Qt and Android
 
Tizen Native Application Development with C/C++
Tizen Native Application Development with C/C++Tizen Native Application Development with C/C++
Tizen Native Application Development with C/C++
 
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
 
Starting Development for Nokia N9
Starting Development for Nokia N9Starting Development for Nokia N9
Starting Development for Nokia N9
 
Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Framework
 
Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009
 
WebGL and three.js
WebGL and three.jsWebGL and three.js
WebGL and three.js
 
Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.js
 
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQtPyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt
 
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
 
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
 
서버 개발자가 되기 전에 알았으면 좋았을 것들
서버 개발자가 되기 전에 알았으면 좋았을 것들서버 개발자가 되기 전에 알았으면 좋았을 것들
서버 개발자가 되기 전에 알았으면 좋았을 것들
 
금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014금융 데이터 이해와 분석 PyCon 2014
금융 데이터 이해와 분석 PyCon 2014
 
WebGL and Three.js
WebGL and Three.jsWebGL and Three.js
WebGL and Three.js
 
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
 

Ähnlich wie Qt Workshop

Integrazione QML / C++
Integrazione QML / C++Integrazione QML / C++
Integrazione QML / C++Paolo Sereno
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
Porting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - WebinarPorting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - WebinarICS
 
Porting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - WebinarPorting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - WebinarJanel Heilbrunn
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyManageIQ
 
03 - Qt UI Development
03 - Qt UI Development03 - Qt UI Development
03 - Qt UI DevelopmentAndreas Jakl
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfPrabindh Sundareson
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkZachary Blair
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196Mahmoud Samir Fayed
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 

Ähnlich wie Qt Workshop (20)

Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
Integrazione QML / C++
Integrazione QML / C++Integrazione QML / C++
Integrazione QML / C++
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Porting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - WebinarPorting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - Webinar
 
Porting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - WebinarPorting Motif Applications to Qt - Webinar
Porting Motif Applications to Qt - Webinar
 
Qt
QtQt
Qt
 
Treinamento Qt básico - aula III
Treinamento Qt básico - aula IIITreinamento Qt básico - aula III
Treinamento Qt básico - aula III
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 
03 - Qt UI Development
03 - Qt UI Development03 - Qt UI Development
03 - Qt UI Development
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application Framework
 
mobl
moblmobl
mobl
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Day 5
Day 5Day 5
Day 5
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 

Mehr von Johan Thelin

Degrees of Freedom
Degrees of FreedomDegrees of Freedom
Degrees of FreedomJohan Thelin
 
Hacktoberfest - An Open Source Story
Hacktoberfest - An Open Source StoryHacktoberfest - An Open Source Story
Hacktoberfest - An Open Source StoryJohan Thelin
 
Open Source on Wheels - Tech Day by Init 2017
Open Source on Wheels - Tech Day by Init 2017Open Source on Wheels - Tech Day by Init 2017
Open Source on Wheels - Tech Day by Init 2017Johan Thelin
 
Qt Automotive Suite - under the hood // Qt World Summit 2017
Qt Automotive Suite - under the hood // Qt World Summit 2017Qt Automotive Suite - under the hood // Qt World Summit 2017
Qt Automotive Suite - under the hood // Qt World Summit 2017Johan Thelin
 
QtWS15 Revolutionizing Automotive with Qt
QtWS15 Revolutionizing Automotive with QtQtWS15 Revolutionizing Automotive with Qt
QtWS15 Revolutionizing Automotive with QtJohan Thelin
 
Building the QML Run-time
Building the QML Run-timeBuilding the QML Run-time
Building the QML Run-timeJohan Thelin
 
Necessitas - Qt on Android - from FSCONS 2011
Necessitas - Qt on Android - from FSCONS 2011Necessitas - Qt on Android - from FSCONS 2011
Necessitas - Qt on Android - from FSCONS 2011Johan Thelin
 
Introduction to Qt Embedded
Introduction to Qt EmbeddedIntroduction to Qt Embedded
Introduction to Qt EmbeddedJohan Thelin
 

Mehr von Johan Thelin (8)

Degrees of Freedom
Degrees of FreedomDegrees of Freedom
Degrees of Freedom
 
Hacktoberfest - An Open Source Story
Hacktoberfest - An Open Source StoryHacktoberfest - An Open Source Story
Hacktoberfest - An Open Source Story
 
Open Source on Wheels - Tech Day by Init 2017
Open Source on Wheels - Tech Day by Init 2017Open Source on Wheels - Tech Day by Init 2017
Open Source on Wheels - Tech Day by Init 2017
 
Qt Automotive Suite - under the hood // Qt World Summit 2017
Qt Automotive Suite - under the hood // Qt World Summit 2017Qt Automotive Suite - under the hood // Qt World Summit 2017
Qt Automotive Suite - under the hood // Qt World Summit 2017
 
QtWS15 Revolutionizing Automotive with Qt
QtWS15 Revolutionizing Automotive with QtQtWS15 Revolutionizing Automotive with Qt
QtWS15 Revolutionizing Automotive with Qt
 
Building the QML Run-time
Building the QML Run-timeBuilding the QML Run-time
Building the QML Run-time
 
Necessitas - Qt on Android - from FSCONS 2011
Necessitas - Qt on Android - from FSCONS 2011Necessitas - Qt on Android - from FSCONS 2011
Necessitas - Qt on Android - from FSCONS 2011
 
Introduction to Qt Embedded
Introduction to Qt EmbeddedIntroduction to Qt Embedded
Introduction to Qt Embedded
 

Kürzlich hochgeladen

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Kürzlich hochgeladen (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Qt Workshop

  • 1. . An Introduction to Qt and Workshop Qt in Education
  • 2. http://www.pelagicore.com/documents/2011-Apr-QtWorkshop.odp © 2011 Nokia Corporation and its Subsidiary(-ies). The enclosed Qt Materials are provided under the Creative Commons Attribution-Share Alike 2.5 License Agreement. The full license text is available here: http://creativecommons.org/licenses/by-sa/2.5/legalcode . Nokia, Qt and the Nokia and Qt logos are the registered trademarks of Nokia Corporation in Finland and other countries worldwide.
  • 3.
  • 4. Thesis work within embedded Linux, open source and design
  • 5.
  • 6.
  • 7.
  • 8. All code is still plain C++ foreach (int value, intList) { … } QObject *o = new QPushButton; o->metaObject()->className(); // returns ”QPushButton” connect(button, SIGNAL(clicked()), window, SLOT(close()));
  • 9.
  • 12.
  • 14. Maemo
  • 15.
  • 16.
  • 18. Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
  • 19. Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
  • 20. Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
  • 21. Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
  • 22. Hello World #include <QApplication> #include <QLabel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QLabel l( &quot;Hello World!&quot; ); l.show(); return app.exec(); }
  • 23.
  • 24. They are placed in a hierarchy of QObject instances
  • 25. They can have connections to other QObject instances
  • 26. Example: does it make sense to copy a widget at run-time? “ QObject instances are individuals!”
  • 27.
  • 28. Every QObject has a meta object
  • 29.
  • 33. general information ( QObject::classInfo )
  • 34.
  • 35. When a parent object is deleted, it deletes its children QObject *parent = new QObject(); QObject *child1 = new QObject(parent); QObject *child2 = new QObject(parent); QObject *child1_1 = new QObject(child1); QObject *child1_2 = new QObject(child1); delete parent;
  • 36.
  • 37.
  • 38. Allocate parent on the stack void Widget::showDialog() { Dialog dialog; if (dialog.exec() == QDialog::Accepted) { ... } } Dialog::Dialog(QWidget *parent) : QDialog(parent) { QGroupBox *box = QGroupBox(this); QPushButton *button = QPushButton(this); QRadioButton *option1 = QRadioButton(box); QRadioButton *option2 = QRadioButton(box); ...
  • 39.
  • 40. Heap memory must be explicitly freed using delete to avoid memory leaks.
  • 41. Objects allocated on the heap can live for as long as they are needed. new delete Construction Destruction
  • 42.
  • 43. Stack variables are automatically destructed when they go out of scope.
  • 44. Objects allocated on the stack are always destructed when they go out of scope. int a } Construction Destruction
  • 45.
  • 46.
  • 48. Signals and Slots in Action emit clicked();
  • 49. Signals and Slots in Action private slots: void on_addButton_clicked(); void on_deleteButton_clicked(); connect(clearButton,SIGNAL(clicked()),listWidget,SLOT(clear())); connect(addButton,SIGNAL(clicked()),this,SLOT(...)); 2x clear();
  • 50. Signals and Slots in Action { ... emit clicked(); ... } { ... emit clicked(); ... } { ... emit clicked(); ... } { QString newText = QInputDialog::getText(this, &quot;Enter text&quot;, &quot;Text:&quot;); if( !newText.isEmpty() ) ui->listWidget->addItem(newText); } { foreach (QListWidgetItem *item, ui->listWidget->selectedItems()) { delete item; } } clear();
  • 51.
  • 52. A slot can return values, but not through connections
  • 53. Any number of signals can be connected to a slot
  • 54. It is implemented as an ordinary method
  • 55. It can be called as an ordinary method public slots: void aPublicSlot(); protected slots: void aProtectedSlot(); private slots: void aPrivateSlot(); connect(src, SIGNAL(sig()), dest, SLOT(slt()));
  • 56.
  • 57. A signal always returns void
  • 58.
  • 59. Usually results in a direct call, but can be passed as events between threads, or even over sockets (using 3 rd party classes)
  • 60. The slots are activated in arbitrary order
  • 61. A signal is emitted using the emit keyword signals: void aSignal(); emit aSignal();
  • 62. Making the connection QObject::connect( src, SIGNAL( signature ), dest, SLOT( signature ) ); <function name> ( <arg type>... ) clicked() toggled(bool) setText(QString) textChanged(QString) rangeChanged(int,int) setTitle(QString text) setValue(42) A signature consists of the function name and argument types. No variable names, nor values are allowed. Custom types reduces reusability. setItem(ItemClass)
  • 63.
  • 64.
  • 65. Triggered by calling QMetaObject::connectSlotsByName
  • 66.
  • 67.
  • 68.
  • 71. Basic file management Open, Save and Save As We will run out of time!
  • 72. Goal of the day
  • 73.
  • 74. Use the QtCore and QtGui modules
  • 75. Base the skeleton project on a QMainWindow
  • 76.
  • 77. mainwindow.ui – the user interface of the main window
  • 78. mainwindow.h/cpp – the class declaration and implementation of the main window
  • 79. main.cpp – the main function, getting everything initialized and running
  • 80.
  • 81. Features will be added to the application, while maintaining a functioning application through-out the process
  • 82. This is how most software is being built in real life!
  • 83.
  • 84.
  • 85.
  • 86.
  • 87. For each of these user actions, a QAction object will be created
  • 88.
  • 89. Do not forget tooltips, statusbar tips, etc. Ctrl+S Action
  • 90.
  • 91.
  • 92. icon – icon to be used everywhere
  • 93. shortcut – shortcut
  • 94. checkable / checked – if the action is checkable and the current check status
  • 95. toolTip / statusTip – tips text for tool tips (hover and wait) and status bar tips (hover, no wait)
  • 96. Why QAction QAction *action = new QAction( parent ); action->setText(&quot;text&quot;); action->setIcon(QIcon(&quot;:/icons/icon.png&quot;)); action->setShortcut(QKeySequence(&quot;Ctrl+G&quot;)); action->setData(myDataQVariant); Setting properties for text, icon and keyboard short-cut Creating a new action A QVariant can be associated with each action, to carry data associated with the given operation
  • 97.
  • 98.
  • 99. Action icons can be added either from files or resources
  • 100.
  • 101. No need to trying to determine the path for the icons for each specific install type
  • 102. All fits neatly into the build system
  • 103. ...
  • 104. You can add anything into resources, not only icons
  • 105.
  • 106. When having added the resource file, make sure to close any Designer forms and re-open them for Designer to discover the resource
  • 107.
  • 108. Before any resources can be added to the resource file, you must first create a directory in the resource file
  • 109. In this case we put icons into the /icons directory
  • 110.
  • 111. Click “...” next to the icon setting
  • 112.
  • 113.
  • 114. To add them to the toolbar, simply drag and drop
  • 115.
  • 116.
  • 117.
  • 118. Slots are generated on the fly in both header and implementation
  • 119. Implementing the new slot is easy – just create a new MainWindow and show it void MainWindow::on_actionNew_triggered() { MainWindow *w = new MainWindow(); w->show(); }
  • 120. Closing and Exiting MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(close())); connect(ui->actionExit, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); } Setting the WA_DeleteOnClose attribute makes the widget delete itself when it is closed All widgets has a close slot out-of-the-box The QApplication class has a slot for closing all windows The qApp pointer refers to the current QApplication instance
  • 121.
  • 122. New windows can be created
  • 123. Windows can be closed
  • 124. The application can exit (i.e. close all windows)
  • 125.
  • 126. The expected behavior would be to ask the user before close a modified document
  • 127. To implement this, we add a modified flag which is set whenever the text of the QTextEdit is changed
  • 128. We also intercept close events and ask the user before closing modified events
  • 129.
  • 130.
  • 131.
  • 132.
  • 133. QWidget provides virtual methods for the most common events, e.g. QWidget::closeEvent
  • 134.
  • 135.
  • 140. about dialogs for both the current application and Qt itself Roughly the same type of dialogs with a title, a message and one or more buttons. The green words are function names for static members. To show an information dialog, use QMessageBox::information , etc.
  • 141. QMessageBox QMessageBox::warning(this, &quot;Document Modified&quot;, &quot;The document has been modified, do you want to close it?&quot; &quot;You will lose all your changes.&quot;, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes Parent window Dialog title The message of the dialog. Notice the use of ' ' The buttons to use. Pick from Ok , Open , Save , Cancel , Close , Discard , Apply , Reset , Restore defaults , Help , Save all , Yes , Yes to all , No , No to all , Abort , Retry and Ignore The default button The return value is the button used for closing the dialog
  • 142.
  • 143. By setting a window title with the sub-string “ [*] ”, the modified indication can be activated using setWindowModified . void MainWindow::updateWindowTitle() { setWindowTitle(tr(&quot;%1 [*] &quot;).arg(qApp->applicationName())); setWindowModified(m_modified); } This function is called from the constructor as well as from the documentModified slot
  • 144.
  • 145. The QApplication object keeps track of the application's name, version, producer, etc.
  • 146. This is used for window titles, etcetera a.setApplicationName(&quot;Text Editor&quot;); a.setApplicationVersion(&quot;0.1&quot;); a.setOrganizationName(&quot;ExampleSoft&quot;); a.setOrganizationDomain(&quot;example.com&quot;); a.setWindowIcon(QIcon(&quot;:/icons/new.png&quot;)); Application icon Producer name and domain Application name and version
  • 147.
  • 148. New windows can be created
  • 149. Windows can be closed
  • 150. The application can exit (i.e. close all windows)
  • 151. We can keep track of document modifications
  • 152. A window cannot be closed without accepting the loss of document modifications
  • 153.
  • 154. We add an action, add a View menu and put the action in the menu Text Name Icon Short-cut Tool-tip Select Font... actionSelectFont Select the display font New menus are always placed to the right, but they can be dragged in to place afterwards
  • 155.
  • 156.
  • 157. The user expects settings to stick, i.e. use the last value when opening new windows
  • 158.
  • 159. By using a QSettings object, you get a cross platform interface for handing settings
  • 160. Any QVariant can be stored – but think about readability for advanced users QSettings settings; myString = settings.value(&quot;key&quot;,&quot;default&quot;).toString(); settings.setValue(&quot;key&quot;, myString); settings.remove(&quot;key&quot;);
  • 161.
  • 162. Restoring the font void MainWindow::on_actionSelectFont_triggered() { bool ok; QFont font = QFontDialog::getFont(&ok, ui->textEdit->font(), this); if(ok) { QSettings settings; settings.setValue(&quot;viewFont&quot;, font); ui->textEdit->setFont(font); } } MainWindow::MainWindow(QWidget *parent) : ... { ... QSettings settings; ui->textEdit->setFont( settings.value(&quot;viewFont&quot;, QApplication::font()).value<QFont>()); ... Default value
  • 164.
  • 165. New windows can be created
  • 166. Windows can be closed
  • 167. The application can exit (i.e. close all windows)
  • 168. We can keep track of document modifications
  • 169. A window cannot be closed without accepting the loss of document modifications
  • 172.
  • 173. The actions are added to both the tool bar and menu Right click on the tool bar to add separators Text Name Icon Short-cut Tool-tip Cut actionCut Ctrl+X Cut Copy actionCopy Ctrl+C Copy Paste actionPaste Ctrl+V Paste
  • 174.
  • 175. To avoid trying to copy in vain, let's add connections for enabling and disabling the actions depending on the selection connect(ui->actionCut, SIGNAL(triggered()), ui->textEdit, SLOT(cut())); connect(ui->actionCopy, SIGNAL(triggered()), ui->textEdit, SLOT(copy())); connect(ui->actionPaste, SIGNAL(triggered()), ui->textEdit, SLOT(paste())); connect(ui->textEdit, SIGNAL(copyAvailable(bool)), ui->actionCut, SLOT(setEnabled(bool))); connect(ui->textEdit, SIGNAL(copyAvailable(bool)), ui->actionCopy, SLOT(setEnabled(bool)));
  • 176.
  • 177.
  • 178. New windows can be created
  • 179. Windows can be closed
  • 180. The application can exit (i.e. close all windows)
  • 181. We can keep track of document modifications
  • 182. A window cannot be closed without accepting the loss of document modifications
  • 185. The expected clipboard actions: cut, copy and paste
  • 187.
  • 188.
  • 189. When a document is loaded
  • 190.
  • 191.
  • 193. Saving QFile file(m_fileName); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) qFatal(&quot;Error opening file for writing&quot;); QTextStream out(&file); out << textString; QFile file(m_fileName); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) qFatal(&quot;Error opening file for reading&quot;); QTextStream in(&file); in >> textString;
  • 194.
  • 195. As a start, it is set in the constructor MainWindow::MainWindow( const QString &fileName , QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_modified(false), m_fileName(fileName) { ... if(!m_fileName.isNull()) loadFile(); updateWindowTitle(); } The name can be QString() , i.e. null, as new, unnamed documents needs this
  • 196.
  • 197.
  • 198. testing.txt - Text Editor void MainWindow::updateWindowTitle() { setWindowTitle(tr(&quot;%1[*] - %2&quot;) .arg(m_fileName.isNull()?&quot;untitled&quot;:QFileInfo(m_fileName).fileName()) .arg(QApplication::applicationName())); setWindowModified(m_modified); } Extracts the file name part of a file name with a path
  • 199.
  • 200. It attempts to load the current file
  • 201. If it fails, it sets the current filename to null void MainWindow::loadFile() { QFile file(m_fileName); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, QApplication::applicationName(), tr(&quot;Could not open file %1.%2&quot;) .arg(QFileInfo(m_fileName).fileName()) .arg(file.errorString())); m_fileName = QString(); } else { QTextStream in(&file); ui->textEdit->setText(in.readAll()); } m_modified = false; updateWindowTitle(); }
  • 202.
  • 203. It attempts to load the current file
  • 204. If it fails, it sets the current filename to null void MainWindow::loadFile() { QFile file(m_fileName); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, QApplication::applicationName(), tr(&quot;Could not open file %1.%2&quot;) .arg(QFileInfo(m_fileName).fileName()) .arg(file.errorString())); m_fileName = QString(); } else { QTextStream in(&file); ui->textEdit->setText(in.readAll()); } m_modified = false; updateWindowTitle(); }
  • 205.
  • 206. It attempts to load the current file
  • 207. If it fails, it sets the current filename to null void MainWindow::loadFile() { QFile file(m_fileName); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, QApplication::applicationName(), tr(&quot;Could not open file %1.%2&quot;) .arg(QFileInfo(m_fileName).fileName()) .arg(file.errorString())); m_fileName = QString(); } else { QTextStream in(&file); ui->textEdit->setText(in.readAll()); } m_modified = false; updateWindowTitle(); }
  • 208.
  • 209. It attempts to load the current file
  • 210. If it fails, it sets the current filename to null void MainWindow::loadFile() { QFile file(m_fileName); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, QApplication::applicationName(), tr(&quot;Could not open file %1.%2&quot;) .arg(QFileInfo(m_fileName).fileName()) .arg(file.errorString())); m_fileName = QString(); } else { QTextStream in(&file); ui->textEdit->setText(in.readAll()); } m_modified = false; updateWindowTitle(); }
  • 211.
  • 212.
  • 213. The actions are added to the File menu and tool bar Text Name Icon Short-cut Tool-tip Open... actionOpen Ctrl+O Open a document Save actionSave Ctrl+S Save the current document Save As... actionSaveAs Ctrl+Shift+S Save current document as
  • 214.
  • 215.
  • 216.
  • 217.
  • 218. Save As sets a name and attempts to save
  • 219. Save is one of the options when a modified document is closed
  • 220. Save As can be canceled
  • 222. Saving documents bool MainWindow::saveFile() { if(m_fileName.isNull()) return saveFileAs(); QFile file(m_fileName); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(...); m_fileName = QString(); updateWindowTitle(); return false; } QTextStream out(&file); out << ui->textEdit->toPlainText(); m_modified = false; updateWindowTitle(); return true; } If the name is null, we need to save as Save the document If the file cannot be opened for writing, we display a warning and set the file name to null Update the modified flag and title Return true on success
  • 223. Saving documents bool MainWindow::saveFileAs() { QString fileName = QFileDialog::getSaveFileName(...); if(!fileName.isNull()) { m_fileName = fileName; return saveFile(); } return false; } Ask the user for a file name If a name is given, attempt to save If no name is given, the save is a failure The method saveFileAs never calls saveFile unlese !fileName.isNull() thus there is no risk for infinite recursion
  • 224.
  • 225.
  • 226. Saving documents void MainWindow::closeEvent(QCloseEvent *e) { if(m_modified) { switch(QMessageBox::warning(this, &quot;Document Modified&quot;, &quot;The document has ...&quot;, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel)) { case QMessageBox::Yes: if(saveFile()) e->accept(); else e->ignore(); break; case QMessageBox::No: e->accept(); break; case QMessageBox::Cancel: e->ignore(); break; } } else { e->accept(); } } The user wants to save The user do not want to save Cancel the closing Close unmodified documents Depending on the save, close or ignore
  • 227.
  • 228. New windows can be created
  • 229. Windows can be closed
  • 230. The application can exit (i.e. close all windows)
  • 231. We can keep track of document modifications
  • 232. A window cannot be closed without accepting the loss of document modifications
  • 235. The expected clipboard actions: cut, copy and paste
  • 239. Thank you for your attention! [email_address]

Hinweis der Redaktion

  1. Qt, is a cross platform development framework written in C++. This does not limit the languages used. Bindings are available for Python, Ruby, C# (mono), Ada, Pascal, Perl, PHP (see: http://qt.nokia.com/products/programming-language-support ) Most people know Qt for its cross platform user interface abilities. Cross platform development is about so much more. For instance, just compare file paths between Windows and Unix. Qt provides classes for almost all conceivable tasks.
  2. Qt supports a multitude of functions in a cross platform manner. This means that Qt is a large package. Qt is divided into modules, and when building and deploying, you can choose which module to use. This helps reducing the number of bytes needed to deploy. Also, there are a few platform specific modules (e.g. QtDBUS for inter process communication – unix only, QtAxContainer and QtAxServer for building and using ActiveX components – Windows only)
  3. Qt extends C++ while sticking to pure C++. Examples of what you get (there is much more): “ foreach” loops Meta-information, great for casting, working with dynamic trees of classes, etc. Using meta-information, dynamic connections such as the connect example is possible.
  4. Qt is available for all major desktop platforms. Windows XP/Vista/7 are officially supported OS X, latest version of Qt supports at least down to 10.3 (10.4 or later is required for development) Linux/Unix with X11, i.e. not tied to Linux. Official support for Linux, AIX, HPUX, Solaris. Community support for FreeBSD, OpenBSD, NetBSD, etc. Notice that the X11 support is not focused to deploying KDE on all desktops. Instead, Qt aims to integrate as a native part of all desktops, including Gnome.
  5. Qt is also available for a number of embedded platforms. Windows CE, versions 5 and 6. Symbian S60, well tested with 3.1, 3.2 and 5.0. Maemo, so you can use it on your N900 tablets Embedded Linux, using the framebuffer directly, i.e. no X11 and a smaller footprint. Can accelerate on some platforms. A nice example is the beagleboard. Tier 3 platforms: QNX, WxWorks. Supported by partner companies.
  6. Qt is also available for a number of embedded platforms. Windows CE, versions 5 and 6. Symbian S60, well tested with 3.1, 3.2 and 5.0. Maemo, so you can use it on your N900 tablets Embedded Linux, using the framebuffer directly, i.e. no X11 and a smaller footprint. Can accelerate on some platforms. A nice example is the beagleboard. Tier 3 platforms: QNX, WxWorks. Supported by partner companies.
  7. Walkthrough The target of the project This will be the starting point of the exercises for this lecture.
  8. Walkthrough The entire source, focus on: - simplicity - small code
  9. Walkthrough Focus on includes. All Qt classes are included by name, compare with iostream, etc. No “.h” ending, capitalization.
  10. Walkthrough One QApplication object, drives the application, manages global settings. There must always be a QApplication object. You can always access the QApplication object through the qApp pointer. You can look at this as a singleton, but the instantiation must be made explicitly from the main function.
  11. Walkthrough QLabel, is a widget. The text is passed to the constructor before the widget is shown. Elaborate, everything is built from widgets. Widgets can be labels (as here), buttons, sliders, group boxes, windows, etc. As the label does not have a parent widget, i.e. it is not contained by another widget, it is a top-level widget. This means that it will result in a new window that is decorated by the native window manager.
  12. Walkthrough Calling exec start the event loop. This gets everything running. The event loop ends when last window closes (can be turned off). Having started the event loop, you must change mind-set. Everything from here on is event driven, be it user interaction (keys or mouse), network or timer.
  13. So, why cannot QChar be a QObject. QObjects are individuals! This means that you cannot write obj1 = obj2, copy is not a valid operation. Why? QObjects have names, for instance addButton, deleteButton, etc (from the first lecture&apos;s demo). How do you copy this? You don&apos;t want two addButtons? QObjects are structured in hierarchies. How do you copy that context? Do you want them at the same level? Leaf level? Root level? QObjects can be interconnected (add calls a slot) How do you copy this? Do you want to duplicate connections?
  14. QObjects carry meta-data, that is data about the object itself. This makes it possible to add introspection to Qt, for instance to ask a class which methods it has Every QObject has a meta object which can be retreived using the metaObject method. The meta object knows about the class, its name, base class, properties, methods, slots and signals. Continues
  15. QObjects can be used in a way that takes care of all the dirty parts of memory management. It becomes almost as easy as working with a garbage collector, but you are still in full control. The trick is that all QObjects have a parent, or an owner. When the parent is deleted, it deletes all its children. This reduces the number of objects that you need to keep track of to one, in the ideal case. Continues
  16. The very same parent-child relationship is used to represent visual hierarchies. Refer to the tree structure, the box contains the radio buttons (option1/2). The parent contains the box and the button. Compare to the previous slide. Continues
  17. So, how does this make memory management easy. I still need to keep track of an object and make sure that I delete it? No, not if you use the stack cleverly. First of all, the example from the previous slide would probably have been implemented in the parent&apos;s constructor, i.e. this is the top-level parent. Second, when using the dialog, you allocate it on the stack. This means that the dialog, along with all its children, will be deleted when the scope ends. Continues
  18. These slides intend to jog the students&apos; memory, not explain the stack vs heap decision in full. The heap is used when you allocate memory dynamically . In C++, that means new/delete. In C you have used malloc and free. Heap memory must be explicitly freed, i.e. you must call delete on everything that you allocate. If you do not do so, you will leak memory. This will, eventually, lead to memory shortage and a crash. Dynamically allocated objects live until you delete them, so you have full control of when something is constructed or destructed. Continues
  19. The stack is used for automatic memory allocations (as opposed to dynamic memory). The stack grows and shrinks when you make function calls. It is used for local variables, function arguments and return addresses. Objects allocated on the stack are destructed when they go out of scope. The scope ends with a }, or return, or for single-line scopes, at the end of the line. Continues
  20. To get almost automatic memory management using Qt, the trick is to allocate the outermost parents on the stack, and the rest on the heap. For instance, the main function scope will be valid for as long as the application is running, so we allocate the application and window on the stack. The window, in turn, creates a bunch of child widgets in its constructor. To avoid destruction when the scope of the constructor ends, they are allocated dynamically. But, they are given the window as their parent object and are thus also destructed when the main function scope ends.
  21. One of the key factors of Qt is the signals and slots mechanism. It is a mechanism to dynamically and loosely tie together events and changes with reactions Dynamically = at run-time Loosely = sender and receiver do not know each other events = timer event, clicks, etc. Not to be confused with actual events (QEvent). state changes = size changed, text changed, value changed, etc reactions = source code that actually does something This is what makes a Qt application tick Continues
  22. Looking at an example from the first lecture. The three buttons all emit the clicked signal when they are clicked by the user (or activated by other means). They do this regardless whether something is connected to them or not, and regardless of what is connected to them. Continues
  23. We choose to connect the buttons to the list widget&apos;s clear slot, and two custom slots in our custom code. As said earlier, the buttons do not care what they are connected to, and the slots are equally independent of what triggers them. You can even call them programatically as ordinary functions. Continues
  24. So, the add button emits clicked, ending up in the on_addButton_clicked slot resulting in the following code being run. It simply asks for input and then adds it to the list. The delete button emits clicked, ending up in the on_deleteButton_clicked slot, where all selected items are deleted. The clear button emits clicked, which ends up in the clear slot of the QListWidget, which to us is a black box that does what its documentation says.
  25. A slot is an ordinary function, just that it can be connected to signals. They do not have to be connected, you can call a slot like any other function, and you implement it as usual. Slots are declared in one of the sections public, protected and private slots. These access restrictions work as intended when calling the function, but a private or protected slot can be connected to any other signal, so they can be triggered from outside the class. Slots can return values, but connections cannot carry return arguments. Any number of signals can be connected to a single slot. This means that a single slot can serve several sources of events – think keyboard shortcut, button, etc. Continues
  26. Signals are defined in the signals section. This section can be considered protected, as a signal can only be emitted from within a class or its decendants. Signals always return void, and must not be implemented. Instead, moc provides function bodies that trigger the actual slot-activation-code. A signal can be connected to any number of slots, so a single event can trigger multiple reactions. It is fully possible to connect signals and slots across threads. Third party libraries such as Qxt ( http://doc.libqxt.org/0.5.0/classQxtRPCPeer.html ). Inside a signal emitting class, you use the emit keyword to emit a signal. The emit keyword is defined as nothing, what actually takes place is a call to the signal function which calls the slots. Continues
  27. You can make signals to slots connections between any two QObjects. Qt verifies that the signatures of the signal and slot match. The signature consists of the name of the signal or slot followed by the argument types . There must be no values nor variable names in the signature. It is also recommended to stick to using standard types, e.g. the ItemClass custom type reduces the reusability and should thus be avoided. Continues
  28. When matching signatures, Qt is very forgiving. The basic rule is that Qt cannot create or convert values, but apart from that anything is allowed (i.e. skipping arguments). The examples on the slide demonstrate this. The errors are (from the top): missing the last int (cannot create) QString does not match int (cannot convert) missing the only int (cannot create) Continues
  29. When making connections from Designer to your own source, Qt uses the automatic connection mechanism. It lets signals automatically connect to slots with the corresponding name (structure and examples on the slide). The automatic connections are made when connectSlotsByName is called. That is done at the end of the setupUi function generated by Designer. When using this mechanism, think about reusability. Sometimes handwriting a couple of connect statements can greatly improve readability of the code. Continues
  30. Read clockwise The application stops executing with the last window has been closed...
  31. Mention that OS X removes the [*], instead a dot in the left-most ball is used to indicate if the document is modified or not.
  32. windowtitles should be interpreted as automatic window titles...