Qt For Beginners - Part 4
Doing More
Christopher Probst, Qt Consultant
Integrated Computer Solutions
Visit us at http://ww...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Qt Creator Kit
4
A kit consists of:
● Qt version (path to qmake)
● Debugger
● Compiler
● Target platform
● Build configura...
Kit Selection
● A Qt Creator user can navigate across multiple kits
● Facilitates the management of multiple Qt versions, ...
Project Configuration
Tabs for each project (kit), build and run settings:
6
Ctrl + [1-7]: Switch between various screens
● Welcome Screen
● Edit Mode
● Debug
● etc
Alt + [0-4]: Toggle which output p...
Shortcuts
Specifying your own shortcut keys!
8
Fake Vim
If you miss Vim!
9
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
What is Model/View?
● A design pattern that aims to separate
implementation of the visual interface from the
business logi...
Item-View and Model/View Classes
● To display large sets of indexed data, Qt
provides a Model/View architecture:
Model/Vie...
Model Classes
● The preceding views are given a model
● Qt provides base model classes that the
programmer generally subcl...
Model/View Example
We want to create an iTunes/Napster-like
download tool that concurrently downloads
multiple files:
14
D...
Model Class Example
class DownloadsModel : public QAbstractTableModel
{
Q_OBJECT
public:
DownloadsModel(QObject *parent = ...
Model Talking to the View
QVariant DownloadsModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::Displa...
The Delegate
● If the view provided by Qt does not display the
data visually as desired, we implement a
delegate
● The del...
Delegate Implementation
void ProgressBarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const
QMode...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Localization
20
Code
label->setText(tr("Greeting"));
Tool
lupdate Project File (app.pro)
TRANSLATIONS += app_de.ts CODECFO...
Localization
In C++:
QString s = tr("Text String");
setWindowTitle(tr("File: %1 Line: %2").arg(f).arg(l));
//: This commen...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Loading the QML File
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiAp...
Exporting C++ Objects to QML
class Message : public QObject
{
Q_OBJECT
Q_PROPERTY(QString author READ author WRITE setAuth...
Alternate Way of Exporting C++ Object
#include "user.h"
#include <QApplication>
void main(int argc, char* argv[])
{
QAppli...
When Exporting C++ Object
Accessible from QML:
● Properties
● Signals
● Slots
● Methods marked with Q_INVOKABLE
● Enums re...
Steps to define a new type in QML:
● In C++: Subclass either QObject or QQuickItem
● In C++: Register the type with the QM...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Embedded Development
● Similar to desktop development
● Typically have to use cross-compiler (runs on
desktop, compiles fo...
Embedded Development
● Need drivers for display, touchscreen, etc.
● QML requires OpenGL
● Some key decisions:
○ Choice of...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Best Practices
● Read the Qt documentation, including relevant
examples and demos.
● Have at least a high-level knowledge ...
Best Practices
● Write your code so it is localizable, even if you
have no immediate plans to translate it.
● Always insur...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Introspection Tip
QLabel aLabel;
aLabel.setText("hello world");
aLabel.show();
for (int i=aLabel.metaObject()->propertyOff...
Tip: Finding The Children
// Signature of Function
QList<T> QObject::findChildren(const QString &name = QString(), Qt::
fi...
Exploring Your Enums
enum AppleType {
Big,
Small
};
Q_ENUM(AppleType)
QMetaEnum metaEnum = QMetaEnum::fromType<ModelApple:...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Some suggested next steps for learning Qt:
● Download and install Qt and Qt Creator
● Look at Qt examples and demos; try m...
● Bug tracker: https://bugreports.qt.io/
● Gerrit code review: https://codereview.qt-project.org/
● Mailing lists: http://...
● Using Qt Creator
● Model/View
● Localization
● Integrating QML With C++
● Embedded Development
● Best Practices
● Tips a...
Next Time on Qt for Beginners!
The ICS Qt experts will take your questions on June 23!
Submit questions at http://www.ics....
Upcoming SlideShare
Loading in …5
×

Qt for beginners part 4 doing more

1,228 views

Published on

See the on-demand video at http://bit.ly/qt-beginners-part-4-more

Published in: Technology
  • Be the first to comment

Qt for beginners part 4 doing more

  1. 1. Qt For Beginners - Part 4 Doing More Christopher Probst, Qt Consultant Integrated Computer Solutions Visit us at http://www.ics.com Video Available at: http://bit.ly/qt-beginners-part-4-more Copyright 2016, Integrated Computers Solutions, Inc. This work may not be reproduced in whole or in part without the express written consent of Integrated Computer Solutions, Inc. 1
  2. 2. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 2
  3. 3. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 3
  4. 4. Qt Creator Kit 4 A kit consists of: ● Qt version (path to qmake) ● Debugger ● Compiler ● Target platform ● Build configuration (Qt mkspec) ● Other environment specs
  5. 5. Kit Selection ● A Qt Creator user can navigate across multiple kits ● Facilitates the management of multiple Qt versions, compilers, debuggers ● Ideal cross compilation and deployment to other devices 5
  6. 6. Project Configuration Tabs for each project (kit), build and run settings: 6
  7. 7. Ctrl + [1-7]: Switch between various screens ● Welcome Screen ● Edit Mode ● Debug ● etc Alt + [0-4]: Toggle which output panes are visible ● Sidebar ● Build Issues ● Search Results ● Application Output ● Compile Output F2: Follow the highlighted symbol Ctrl + i: Auto-indent selected code Ctrl + /: Comment selected code Ctrl + tab: Navigate through the files Shortcuts 7
  8. 8. Shortcuts Specifying your own shortcut keys! 8
  9. 9. Fake Vim If you miss Vim! 9
  10. 10. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 10
  11. 11. What is Model/View? ● A design pattern that aims to separate implementation of the visual interface from the business logic that drives it. ● This design pattern is common throughout Qt. ○ Integration of UI files (Qt Designer) ○ Loading of QML files ○ Item-View Classes 11
  12. 12. Item-View and Model/View Classes ● To display large sets of indexed data, Qt provides a Model/View architecture: Model/View/Delegate ● The views are provided by convenience classes 12 QTableView QTreeView
  13. 13. Model Classes ● The preceding views are given a model ● Qt provides base model classes that the programmer generally subclasses. ○ QAbstractItemModel ○ QAbstractListModel ○ QAbstractTableModel 13 ui->DownloadTable->setModel(downloadModel); void QAbstractItemView::setModel(QAbstractItemModel * model)
  14. 14. Model/View Example We want to create an iTunes/Napster-like download tool that concurrently downloads multiple files: 14 Download Manager UI Example
  15. 15. Model Class Example class DownloadsModel : public QAbstractTableModel { Q_OBJECT public: DownloadsModel(QObject *parent = 0); // QAbstractItemModel interface int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; ... private: // Our model “knows” how to access the data for the view QList<Downloads*> DownLoadList; }; 15
  16. 16. Model Talking to the View QVariant DownloadsModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { // Data for first column if (index.column() == 0) { // Data for view QUrl url = DownLoadList.at(index.row())->url(); return url; } // Data for second column else if (index.column() == 1) { // Data for view int progressPercentage = (DownLoadList.at(index.row())->progress() * 100 / DownLoadList.at(index.row())->total()); return progressPercentage; } } return QVariant(); } 16 Through the QAbstractItemModel::data(..) function, the model, given a row and a column, returns the appropriate data
  17. 17. The Delegate ● If the view provided by Qt does not display the data visually as desired, we implement a delegate ● The delegate class is used to specify how data is rendered by the view ● Instead of displaying a number, we want to display a progress bar 17
  18. 18. Delegate Implementation void ProgressBarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() == 1) { int progressPercentage = index.model()->data(index, Qt::DisplayRole).toInt(); QStyleOptionProgressBar progressBarOption; progressBarOption.rect = QRect(option.rect.x() + 5, option.rect.y() + 5, option.rect.width() - 10, option.rect.height() - 10); progressBarOption.minimum = 0; progressBarOption.maximum = 100; progressBarOption.progress = progressPercentage; progressBarOption.text= QString::number(progressPercentage) + "%"; progressBarOption.textAlignment = Qt::AlignCenter; progressBarOption.textVisible = true; if (option.state & QStyle::State_Selected) painter->fillRect(option.rect, option.palette.alternateBase()); QApplication::style()->drawControl( QStyle::CE_ProgressBar, &progressBarOption, painter); } else { QStyledItemDelegate::paint(painter, option, index); } } 18 ProgressBarDelegate* delegate = new ProgressBarDelegate(this); ui->DownloadTable->setItemDelegateForColumn( 1, delegate);
  19. 19. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 19
  20. 20. Localization 20 Code label->setText(tr("Greeting")); Tool lupdate Project File (app.pro) TRANSLATIONS += app_de.ts CODECFORTR = UTF-8 Tool Qt Linguist TS File app_de.ts Tool lrelease QM File app_de.qm Code QTranslator translator; translator. load("app_de"); app.installTranslator (&translator); provide translation 2 load translation 4 extracts translations updates ts file compile translation 3 1
  21. 21. Localization In C++: QString s = tr("Text String"); setWindowTitle(tr("File: %1 Line: %2").arg(f).arg(l)); //: This comment is seen by translation staff label->setText(tr("Name: %1 Date: %2").arg(name, d.toString())); 21 In QML: Button { id: button1 text: qsTr("Press Me") }
  22. 22. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 22
  23. 23. Loading the QML File #include <QGuiApplication> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl("qrc:/main.qml")); return app.exec(); } 23 QT += qml quick CONFIG += c++11 SOURCES += main.cpp RESOURCES += qml.qrc In the .pro file... In the main.cpp file...
  24. 24. Exporting C++ Objects to QML class Message : public QObject { Q_OBJECT Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged) Q_PROPERTY(QDateTime creationDate READ creationDate WRITE setCreationDate NOTIFY creationDateChanged) public: // ... }; 24 qmlRegisterType<Message>("com.mycompany.messaging", 1, 0, "Message"); import com.mycompany.messaging 1.0 Message { author: "Amelie" creationDate: new Date() } Exported file In header file Registering the class in the code before the QML is loaded Using class in QML file
  25. 25. Alternate Way of Exporting C++ Object #include "user.h" #include <QApplication> void main(int argc, char* argv[]) { QApplication app(argc, argv); qmlRegisterType<User>("com.mycompany.qmlcomponents", 1, 0, "User"); User *currentUser = new User("Alice", 29); QQuickView *view = new QQuickView; QQmlContext *context = view->engine()->rootContext(); // Exporting of C++ object happens here context->setContextProperty("_currentUser",currentUser); } 25 Text { text: _currentUser.name ... }
  26. 26. When Exporting C++ Object Accessible from QML: ● Properties ● Signals ● Slots ● Methods marked with Q_INVOKABLE ● Enums registered with Q_ENUM 26
  27. 27. Steps to define a new type in QML: ● In C++: Subclass either QObject or QQuickItem ● In C++: Register the type with the QML environment ● In QML: Import the module containing the new item ● In QML: Use the item like any other standard item ● Non-visual types are QObject subclasses ● Visual types (items) are QQuickItem subclasses ○ QQuickItem is the C++ equivalent of Item 27
  28. 28. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 28
  29. 29. Embedded Development ● Similar to desktop development ● Typically have to use cross-compiler (runs on desktop, compiles for target) ● Don’t underestimate the effort to get environment set up ● Also need to get Qt running optimally on your hardware (can be a significant effort) ● Qt Creator can build for, deploy to, debug, and profile remote targets ● Qt and third party code licensing is more complex for embedded. 29
  30. 30. Embedded Development ● Need drivers for display, touchscreen, etc. ● QML requires OpenGL ● Some key decisions: ○ Choice of platform (e.g. embedded Linux, QNX, etc.) ○ Rendering back end (eglfs, xcb, linuxfb, directfb, etc.) ● Ensure adequate RAM, mass storage, CPU and GPU performance ● Often start by developing UX prototype for desktop ● Don’t delay moving to the embedded platform! 30
  31. 31. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 31
  32. 32. Best Practices ● Read the Qt documentation, including relevant examples and demos. ● Have at least a high-level knowledge of all of Qt's modules. ● Explore third party libraries and components before reinventing the wheel. ● Take the time to properly set up your qmake projects and configure Qt Creator. ● Define a test strategy (e.g. write unit tests). ● Set up an automated build system. 32
  33. 33. Best Practices ● Write your code so it is localizable, even if you have no immediate plans to translate it. ● Always insure your dynamic QObjects have a parent so they are deleted when the parent is. ● Using Qt’s built-in iterators can help prevent accessing bad data in container classes and are compatible with STL algorithms. ● Favor layouts over having your program position the items with coordinates. ● Understand the difference between QDialog():: exec() and QWidget()::show(). 33
  34. 34. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 34
  35. 35. Introspection Tip QLabel aLabel; aLabel.setText("hello world"); aLabel.show(); for (int i=aLabel.metaObject()->propertyOffset(); i < aLabel.metaObject()->propertyCount() ; i++) { qDebug() << "Property Name :" << aLabel.metaObject()->property(i).name(); qDebug() << "Property Value :" << aLabel.property(aLabel.metaObject()->property(i).name()); } 35 // You can add properties to your QObject derived classes by using the // following macro. Q_PROPERTY(type name READ getFunction [WRITE setFunction])
  36. 36. Tip: Finding The Children // Signature of Function QList<T> QObject::findChildren(const QString &name = QString(), Qt:: findChildOptions options = Qt::findChildrenRecursively) const 36 // This example returns all QPushButtons that are children of parentWidget: QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>(); // This example returns all QPushButtons that are immediate children of parentWidget: QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *> (QString(), Qt::findDirectChildrenOnly);
  37. 37. Exploring Your Enums enum AppleType { Big, Small }; Q_ENUM(AppleType) QMetaEnum metaEnum = QMetaEnum::fromType<ModelApple::AppleType>(); qDebug() << metaEnum.valueToKey(ModelApple::Big); 37
  38. 38. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 38
  39. 39. Some suggested next steps for learning Qt: ● Download and install Qt and Qt Creator ● Look at Qt examples and demos; try modifying them ● Read documentation in Qt Assistant (including tutorials) ● Take a course ● Create some small applications of your own ● Join the qt-interest mailing list (and possibly others) ● Report bugs ● Test alpha, beta, RC releases ● Review code ● Submit fixes Where To Go Next 39
  40. 40. ● Bug tracker: https://bugreports.qt.io/ ● Gerrit code review: https://codereview.qt-project.org/ ● Mailing lists: http://lists.qt-project.org/mailman/listinfo ● Wiki: https://wiki.qt.io/ ● Blogs: http://blog.qt.io/ ● Documentation: http://doc.qt.io/ ● Forums: http://forum.qt.io/ ● ICS training: http://www.ics.com/learning/training Where To Go Next 40
  41. 41. ● Using Qt Creator ● Model/View ● Localization ● Integrating QML With C++ ● Embedded Development ● Best Practices ● Tips and Tricks ● Where To Go Next ● Q&A Agenda 41
  42. 42. Next Time on Qt for Beginners! The ICS Qt experts will take your questions on June 23! Submit questions at http://www.ics.com/ask-your-qt- questions or on Twitter with hashtag #QtQuestions 42

×