Alan Crispin's Qt Lecture

21 downloads 2049 Views 694KB Size Report
Qt Core: Contains core non-GUI functionality(all modules in Qt rely on this module). Qt GUI: ... Qt Network: Provides classes for network programming. Qt Qml: ...
Qt Getting Started Dr Alan Crispin

Qt ● ●

Qt is an application framework based on C++ It is used for the rapid development of software on platforms including Microsoft Windows, Linux and Mac OS X



Write code once, compile to multiple platforms



Licences GPL, LGPL, Commercial

Qt SDK Qt Creator, Qt Designer, Qt Assistant, qmake

Qt Class Library (Modular) Qt Core: Contains core non-GUI functionality(all modules in Qt rely on this module) Qt GUI: Extends QtCore with GUI functionality Qt Multimedia: Provides audio, video, radio, and camera functionality Qt Network: Provides classes for network programming Qt Qml: qml and Javascript language module for Qt Qt SQL: Qt support for SQL databases Qt Test: Classes for unit testing Qt WebKit: Web browser engine

Windows

Mac

Linux

Hardware

Embedded

QT Creator

Qt Hello World #include #include int main(int argc, char **argv) { QApplication app(argc, argv);

Pointer created when the new keyword used

//QLabel l("Hello World -Stack"); //l.show();

}

QLabel *aLabel = new QLabel("Hello World -Heap"); aLabel->show(); With a pointer you use the arrow operator to access return app.exec(); member functions

Create a QApplication object called “app” on the stack. Objects created on the stack are destroyed automatically when they go out of scope. Every GUI application has an event loop i.e. app.exec(). A QLabel can be created on either the stack or heap. Qt automatically encapsulates the QLabel inside a window with the show() method.

C++ ●







You need to have a basic knowledge of C++ to create Qt projects C++ applications are written using header (.h) files and source (.cpp) files Some understanding of C++ object oriented concepts (e.g. class, object, overloading, inheritance, overriding etc.) is required Use the web link below to download a –

C++ Quick Start Guide



C++ Basic Object Oriented Concepts Tutorial http://www.tutorialspoint.com/cplusplus/index.htm

QObject ●

● ●

QObject is the base class of almost all Qt classes QWidget extends (is a) QObject Classes which inherit from QObject can use the signals and slot mechanism, properties and the memory management system provided by Qt via the Meta-Object Compiler or moc

Ownership QObject ●









Objects organise themselves in a parent child hierarchy (tree) There is a parent-child ownership relationship When a parent is deleted it will delete all of its children Ownership provides basic memory management Parent/child ownership is not inheritance

QWidget

QLabel

QPushButton

QLineEdit

QMainWindow Menu bar Tool bar

The main window can also incorporate dock windows (windows that are on the side which you can drag)

Central Widget will typically be set to a Qt widget such as a QTextEdit or a QGraphicsView

Status bar QAction Is a command object which has a signal called triggered. You use the same QAction for a menu item and tool bar item

void MainWindow::on_actionExit_triggered() { QApplication::quit(); //:: = scope resolution operator }

Layout Managers ●





Layout Managers are used for geometry management Layout managers can be nested Built-in layout managers include: –

QHBoxLayout



QVBoxLayout



QGridLayout



QFormLayout.

A QHBoxLayout lays out widgets in a horizontal row, from left to right A QVBoxLayout lays out widgets in a vertical column, from top to bottom A QGridLayout lays out widgets in a two-dimensional grid (widgets can occupy multiple cells) A QFormLayout lays out widgets in a 2-column descriptive label- field style

Signals and Slots ●





The Qt pre-compiler (moc) provides a signals and slots mechanism for high level events The signals and slots mechanism is very easy to use and is very flexible –

You can connect one signal to several events



You can connect several signals to one slot

You use the “connect” macro to connect a signal to a slot –





connect(sender,signal,receiver,slot)

A slot is a standard C++ function You only need to specify a signal (i.e. you do not write code to emit a signal)

Signals and Slots Signal called valueChanged(int) emitted from the slider

Signal consumed by progress bar setValue(int) slot

Signal consumed by lcdNumber display(int) slot

Signals and Slots Demo MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Signals and Slots Demo"); connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),ui->progressBar,SLOT(setValue(int))); connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),ui->progressBar_2,SLOT(setValue(int))); //disconnect(ui->horizontalSlider,SIGNAL(valueChanged(int)),ui>progressBar_2,SLOT(setValue(int))); connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),ui->progressBar_3,SLOT(setValue(int))); connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),ui->lcdNumber,SLOT(display(int))); }

Common Widgets

QCheckBox Widget ui->checkBox->setChecked(true);

void MainWindow::on_pushButton_clicked() { if (ui->checkBox->isChecked()) { QMessageBox::information(this,"CheckBox Test","CheckBox is ticked"); } else { QMessageBox::information(this,"CheckBox Test","CheckBox is not ticked"); } }

QRadioButton Widget void MainWindow::on_pushButton_2_clicked() { if(ui->radioButton1->isChecked()) { QMessageBox::information(this,"RadioButton Test","Checked RadioButton = " + ui->radioButton1->text()); } if(ui->radioButton2->isChecked()) { QMessageBox::information(this,"RadioButton Test","Checked RadioButton = " + ui->radioButton2->text()); } if(ui->radioButton3->isChecked()) { QMessageBox::information(this,"RadioButton Test","Checked RadioButton = " + ui->radioButton3->text()); } }

QComboBox Widget A QComboBox allows you to select an item from a list of items //Populate comboBox using a for loop for (int i=1; icomboBox->addItem("Qt Version"+QString::number(i)); }

void MainWindow::on_pushButton_3_clicked() { QMessageBox::information(this,"ComboBox Test",ui->comboBox->currentText()); }

Saving and Reading Files

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { //mainwindow constructor ui->setupUi(this); this->setWindowTitle("QFile Demo -Alan Crispin"); this->setCentralWidget(ui->textEdit); }

You use QFile and QTextStream classes to save and read text files and QFileDialog to allow users to select files or directories

Saving Text to File void MainWindow::on_actionSave_triggered() { //The QFileDialog class provides a dialog that allow users to select files or directories QString fileName = QFileDialog::getSaveFileName(this,"Save As File"); QFile saveFile(fileName);//QFile is a class for reading and writing files if (saveFile.open(QFile::WriteOnly | QFile::Text)) //open the saveFile to “writeOnly”, “Text” { QTextStream outStream(&saveFile); //outStream takes a reference (i.e. &) to SaveFile outStream textEdit->toPlainText(); //stream text using the insertion textEdit->setPlainText(text);//set textEdit text } } } void MainWindow::on_actionNew_triggered() { ui->textEdit->setPlainText("");//Clear textEdit widget }

Drawing

You use a QPainter for drawing on a widget by overriding the paintEvent

Paint Event #ifndef MAINWINDOW_H #define MAINWINDOW_H #include #include //QPainter is used for drawing on widgets #include //QPen defines how a QPainter should draw lines of shapes #include //QBrush defines the fill pattern of shapes namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui;

You add this to override the paintEvent

protected: void paintEvent(QPaintEvent *e); //override mainWindow paintEvent }; #endif // MAINWINDOW_H

Paint Event void MainWindow::paintEvent(QPaintEvent *e) { QPainter aPainter(this); QPen blackPen(Qt::black); blackPen.setWidth(2); QBrush redBrush(Qt::red); QBrush blueBrush(Qt::blue); aPainter.setPen(blackPen); aPainter.drawLine(50,0,50,100); //draw line aPainter.setBrush(redBrush); aPainter.drawRect(100,10,200,50);//draw rectangle aPainter.setBrush(blueBrush); aPainter.drawEllipse(10,100, 200,50); //draw ellipse }

Drawing ●

Drawing on widgets must be done using the paintEvent –

QPen – for drawing lines



QBrush – for filling shapes



You use update() to force re-drawing



Qt does double buffering by default



You can draw to a QImage and a QPixMap





QImage -good for image processing



QPixMap -good for icons and background images

You can subclass QWidget and override the paintEvent for drawing applications

QGraphicsView ●







The QGraphicsView class provides a widget for displaying the contents of a QGraphicsScene QGraphicsView visualises the contents of a QGraphicsScene in a scrollable viewport The idea is that you separate the scene model data (i.e. the QGraphicsScene) from the view For coding details see the QGraphicsView demonstration project

QGraphicsView Demonstration You can move the rectangles in the view

Unit Testing ●







Unit testing involves testing individual units of code Qt allows unit testing projects to be created with data driven tests QCOMPARE (actual, expected ) macro –

compares an actual value to an expected value using the equals operator



If actual and expected are identical, execution continues



If not, a failure is recorded in the test log

See unit testing demonstration project for coding details

Morning Exercise (Text Editor)

Download and use the step-by-step exercise sheet to create a text editor application

Afternoon Exercise (Life Simulation)

The initial pattern constitutes the seed of the system

http://en.wikipedia.org/wiki/Conway's_Game_of_Life

Conway's Game of Life ●

Two-dimensional grid of square cells



Every cell interacts with its eight neighbours



Each cell is in one of two possible states, alive or dead



At each step in time, the following rules are used –

Any live cell with fewer than two live neighbours dies, as if caused by under-population



Any live cell with two or three live neighbours lives on to the next generation



Any live cell with more than three live neighbours dies, as if by overcrowding



Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction

Life Simulation

Many different types of patterns occur in the Game of Life, including still lives, oscillators, and patterns that translate themselves across the grid

Extra Exercise (Image Viewer)

Uses the QGraphicsView and QGraphicsScene classes

Extra Exercise (Sorting Data)

Summary ●

Key concepts –

Stack, heap, pointers



QObject, ownership, memory management



QMainWindow, layout managers, widgets



Signals and slots



QFile, QTextStream, QFileDialog



Events (paintEvent, mousePressEvent)



GraphicsView (scene data separated from the view)



Unit Testing

Alan Crispin (Updated May 2014)