Qt for beginners part 4 doing more
-
Upload
ics -
Category
Technology
-
view
976 -
download
1
Transcript of Qt for beginners part 4 doing more
Qt For Beginners - Part 4Doing More
Christopher Probst, Qt ConsultantIntegrated Computer SolutionsVisit 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
● 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
● 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
Qt Creator Kit
4
A kit consists of: ● Qt version (path to qmake)● Debugger● Compiler● Target platform● Build configuration (Qt
mkspec) ● Other environment specs
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
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 panes are visible● Sidebar● Build Issues● Search Results● Application Output● Compile Output
F2: Follow the highlighted symbol
Ctrl + i: Auto-indent selected codeCtrl + /: Comment selected codeCtrl + tab: Navigate through the files
Shortcuts
7
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 and Tricks● Where To Go Next● Q&A
Agenda
10
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
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
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)
Model/View Example
We want to create an iTunes/Napster-like download tool that concurrently downloads multiple files:
14
Download Manager UI Example
Model Class Example
class DownloadsModel : public QAbstractTableModel{ Q_OBJECTpublic: 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
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
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
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);
● 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
Localization
20
Codelabel->setText(tr("Greeting"));
Tool lupdate Project File (app.pro)
TRANSLATIONS += app_de.ts CODECFORTR = UTF-8
ToolQt Linguist
TS File app_de.ts
Tool lrelease
QM File app_de.qm
CodeQTranslator translator; translator.load("app_de"); app.installTranslator(&translator);
provide translation2
load translation4
extracts translations updates ts file
compile translation3
1
Localization
In C++:
QString s = tr("Text String");setWindowTitle(tr("File: %1 Line: %2").arg(f).arg(l));//: This comment is seen by translation stafflabel->setText(tr("Name: %1 Date: %2").arg(name, d.toString()));
21
In QML:
Button { id: button1 text: qsTr("Press Me")}
● 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
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 quickCONFIG += c++11
SOURCES += main.cpp
RESOURCES += qml.qrc
In the .pro file...
In the main.cpp file...
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.0Message { 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
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 herecontext->setContextProperty("_currentUser",currentUser);
}
25
Text {
text: _currentUser.name ... }
When Exporting C++ Object
Accessible from QML:● Properties● Signals● Slots● Methods marked with Q_INVOKABLE● Enums registered with Q_ENUM
26
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
● 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
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
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
● 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
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
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
● 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
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])
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);
Exploring Your Enums
enum AppleType { Big, Small};
Q_ENUM(AppleType)
QMetaEnum metaEnum = QMetaEnum::fromType<ModelApple::AppleType>();qDebug() << metaEnum.valueToKey(ModelApple::Big);
37
● 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
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
● 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
● 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
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-
questionsor on Twitter with hashtag #QtQuestions
42