Continuing where module 2 left off, this part of the course explains signals and slots in more detail and tells you how to extend functionality of existing widgets by subclassing them. In real applications, widgets are often used in dialogs or inside the main window, which is a container for widgets and by default supports menus, toolbars and actions. These topics are all demonstrated via small examples.
4. Qt & Graphics
β’ Available options
β Traditional widgets
β Custom widgets and QPainter
β QGraphicsView
β QGLWidget
β Qt Quick
β QtWebKit
5. Traditional Qt Widgets
β’ QWidget as base of UI components in Qt
β Window management, layouts
β Use native UI design
β Support style sheets
β Ex.: QPushButton,
QLabel, QLineEdit
6. Traditional Qt Widgets
β’ UI Designer support
β Instant preview, drag & drop UI
β Integrated even with translator tool
High level
Exactly the same code on all platforms
Less customization possible, UI effects difficult
Smaller UI, different paradigms
7. QWidget and QPainter
β’ Draw manually using QPainter
β On QWidget surfaces
β Flexible painting: text, gradients, polygons,
bezier curves, transparencies, etc.
Lets you express your painting directly
Traditional
Makes you express your painting directly
8. QGraphicsView
β’ Manage 2D scenes with a scene graph
β Can manage thousands of items with hierarchies
β Collision detection, affine transformations,
drag and drop support
β Hardware acceleration and integration with QWidget possible
High level
Conceptually nice and flexible
No ready-made common UI components available yet
9. MeeGo Touch
β’ UI Framework based on QGraphicsView
β Provides common UI components with
theme support
β Integrates transitions and effects
Great graphics effects, theme support
Easy to create smooth UIs
Already available from source repositories
Still in development
10. QGLWidget
β’ Very low level
β Basic setup by Qt
β You do the hard work Angry Birds and Bounce
by Rovio
Complete control over GL
Good if you have existing codebase & assets, cross-platform
OpenGL is hard work (but thereβs more Qt coming for that *)
No Qt OpenGL for Symbian integration in Qt 4.7.0
* http://doc.qt.nokia.com/qt3d-snapshot/index.html
11. Qt Quick
β’ Several components
β QML language and JavaScript
β Declarative syntax, animations and states integrated
β Available in Qt 4.7+
Very easy to make slick, fluid UIs
Will soon be most important way to create mobile UIs
More tooling is on its way
Ready-made UI components on their way *
* Project page: http://bugreports.qt.nokia.com/browse/QTCOMPONENTS
12. Sample app to integrate web into Qt: http://wiki.forum.nokia.com/index.php/QtWebKitStub
QtWebKit
β’ Open source browser engine
β Display HTML(5) and JavaScript content
through a QWidget
β Combine Qt C++ and web code if needed to
get best of both worlds
Use your existing web skills to create the UI
Reuse web components (online help, etc.)
Complex UIs and interaction probably more difficult
Less performance than native code (but improving)
13. How to Choose?
β’ Depends on
β Complexity of your UI
β Existing code/assets
β Experience with low level code
β Which devices youβre targeting
β Your timeframe
β’ Mix and match as appropriate!
15. Signal and Slots, Continued
β’ How to accomplish the following?
QObject::connect(button, SIGNAL(clicked()),
label, SLOT(setText("new text")));
ο¦ doesnβt work that way, clicked()-signal doesnβt give required number
of arguments to setText()-slot.
16. Custom Widgets (Slots)
β’ Commonly used: subclass widgets to extend functionality
β Class MyWindow is a widget (parent)
β Also manages child widgets
β’ Widget adds new slot
β Put text to display into this slot method
instead of the connect statement
19. Dialogs QObject QPaintDevice
β’ Dialog is:
QWidget
β Top-level window
β Used for short-term tasks, brief user communication
β Can provide return value QDialog
β’ Modal
β Dialog blocks other application windows (e.g., file open dialog)
β Usually called with exec(), returns when dialog is closed
β Call with show(): returns immediately, get results via signals
β’ Modeless
β Operates independently from other windows
(e.g., find & replace dialog)
β Always called with show(): returns immediately
20. Custom Dialog
clicked() signal from button in main widget triggers dialog
Change label in main widget depending on user action selected in dialog
22. The Dialog
myDialog.h myDialog.cpp
#ifndef MYDIALOG_H #include "mydialog.h"
#define MYDIALOG_H
MyDialog::MyDialog()
#include <QDialog> {
#include <QPushButton> setFixedSize(150, 100);
#include <QVBoxLayout> QVBoxLayout* vbox = new QVBoxLayout();
#include <QLabel> QLabel* label = new QLabel("Please confirm.");
QPushButton* okButton = new QPushButton("Ok");
class MyDialog : public QDialog QPushButton* cancelButton = new QPushButton("Cancel");
{
Q_OBJECT // Set the ok button as default
public: okButton->setDefault(true);
MyDialog(); vbox->addWidget(label);
}; vbox->addWidget(okButton);
vbox->addWidget(cancelButton);
#endif // MYDIALOG_H setLayout(vbox);
// Connect the buttons to slots defined by QDialog
connect(okButton, SIGNAL(clicked()),
this, SLOT(accept()));
connect(cancelButton, SIGNAL(clicked()),
this, SLOT(reject()));
}
23. QDialog Base Class
Slot Description
virtual void accept() Hides the dialog and sets the result code to Accepted (1).
virtual void reject() Hides the dialog and sets the result code to Rejected (0).
virtual void done(int r) Closes the dialog and sets return value to r.
If the dialog is started via exec(), done() causes the event loop to finish, and exec() to return r.
Deletes the dialog if Qt::WA_DeleteOnClose is set.
int exec() Shows the dialog as a modal dialog, blocking until the user closes it. Returns dialog return value
(DialogCode) like Accepted or Rejected.
Signal Description
void accepted() Emitted when dialog has been accepted through calling accept() or done() with the argument
QDialog::Accepted
void rejected() Emitted when dialog has been rejected through calling reject() or done() with the argument
QDialog::Rejected
void finished(int result) Emitted when the dialogβs result code has been set (setResult()) and either accept(), reject() or
done() is called.
24. The Widget
mywidget.h mywidget.cpp
[...] #include "mywidget.h"
class MyWidget : public QWidget MyWidget::MyWidget(QWidget *parent) : QWidget(parent) {
{ setWindowTitle("Main Window - Dialog Example");
Q_OBJECT startButton = new QPushButton("Start dialog");
instructionsLabel = new QLabel("Please push the button");
public: resultLabel = new QLabel();
MyWidget(QWidget *parent = 0);
~MyWidget(); layout = new QVBoxLayout(this);
layout->addWidget(instructionsLabel);
private slots: layout->addWidget(startButton);
void checkInputDialog(); layout->addWidget(resultLabel);
private: dialog = new MyDialog();
QPushButton* startButton;
QLabel* instructionsLabel; connect(startButton, SIGNAL(clicked()),
QLabel* resultLabel; dialog, SLOT(exec()));
QVBoxLayout* layout; connect(dialog, SIGNAL(accepted()),
MyDialog* dialog; this, SLOT(checkInputDialog()));
connect(dialog, SIGNAL(rejected()),
}; this, SLOT(checkInputDialog()));
}
#endif // MYWIDGET_H
void MyWidget::checkInputDialog() {
int res = dialog->result(); // Gets result (Accepted/Rejected)
if (res == QDialog::Accepted) {
resultLabel->setText(""Ok" was selected");
} else if (res == QDialog::Rejected) {
resultLabel->setText(""Cancel" was selected");
}
}
27. Predefined Dialogs
β’ Example: Message box
β Modal dialog
β User selection β return value
int ret = QMessageBox::warning( this, "Exit?",
"Do you really want to exit the application?",
QMessageBox::Yes | QMessageBox::No );
29. Main Window
β’ Provides main application window Menu Bar
β Pre-defined layout for standard components Toolbars
β Central widget must be defined, others
Dock Widgets
optional
β Subclass to create your own implementation
Central Widget
β’ Differences?
β Possible with dialog / widgets as well
β But: more comfortable, consistent and efficient
Status Bar
30. Example - QMainWindow
mainwindow.h mainwindow.cpp
[...] #include "mainwindow.h"
class MainWindow : public QMainWindow MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
{ : QMainWindow(parent, flags)
Q_OBJECT {
editor = new QTextEdit();
public: setMinimumSize(160, 160);
MainWindow(QWidget *parent = 0, resize(480, 320);
Qt::WFlags flags = 0); setCentralWidget(editor);
~MainWindow(); setWindowTitle("QMainWindow with Menus");
private: QString message = "Welcome";
QTextEdit* editor; statusBar()->showMessage(message);
}
[...]
};
#endif // MAINWINDOW_H
main.cpp is similar to
the previous example
31. Action
Image by Anna Cervova
(Public Domain)
β’ Represent abstract user interface β’ Stores
action information about
β Define once, use in multiple β Icons
components β Text
β Inserted into widgets β Keyboard shortcut
β’ Menus
(can create actions implicitly)
β Status text
β’ Toolbar buttons β βWhatβs This?β text
β’ Keyboard shortcuts
β Tooltip
32. Menu Bar
β’ QMenu provides:
β a menu widget for menu bars, context menus
and other popup menus
β’ Supports:
β Triggered Items
β Separators
β Submenus
β Tear-off menus
β’ QMenuBar automatically created by
QMainWindow
β’ QMenu(s) contains individual menu items (ο¦
Actions)
33. Example β QAction
mainwindow.h mainwindow.cpp
[...] [...]
// Create a new βOpenβ action with an icon, keyboard shortcut and
class MainWindow // info-text for the status bar.
: public QMainWindow openAct = new QAction("&Open...", this);
{ openAct->setIcon(QIcon("images/open.png"));
Q_OBJECT openAct->setShortcut(tr("Ctrl+O"));
[...] openAct->setStatusTip(tr("Open an existing file"));
connect(openAct, SIGNAL(triggered()), this, SLOT(openFile()));
private slots:
void openFile(); // Add the action to the menu
fileMenu = menuBar()->addMenu(tr("&File"));
private: fileMenu->addAction(openAct);
QMenu *fileMenu;
QAction *openAct; [...]
};
void MainWindow::openFile()
{
// Define two filter options β one for documents, one for all files
// The filter mask is automatically parsed, β;;β separates lines
QString file = QFileDialog::getOpenFileName(this,
"Please choose a file to open", QDir::homePath(),
"Documents (*.pdf *.doc *.docx);;All files (*.*)");
if (!file.isNull())
{
QString info("You chose this filen");
info.append(file);
QMessageBox::information(this, "Your Choice", info, QMessageBox::Ok);
}
}
34. Toolbar
β’ Same actions as for menu can be used for toolbar
β’ Default automatically enables drag & drop
35. Example β QToolBar
mainwindow.h mainwindow.cpp
[...] #include "mainwindow.h"
class MainWindow MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
: public QMainWindow : QMainWindow(parent, flags) {
{ [...]
Q_OBJECT // Open action
[...] openAct = new QAction("&Open...", this);
openAct->setIcon(QIcon("images/open.png"));
private: openAct->setShortcut(tr("Ctrl+O"));
QToolBar *toolFile; openAct->setStatusTip(tr("Open an existing file"));
}; connect(openAct, SIGNAL(triggered()), this, SLOT(openFile()));
// Exit action
exitAct = new QAction("E&xit", this);
exitAct->setIcon(QIcon("images/exit.png"));
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit the application"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
// Create the file menu
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
// Add the actions to the toolbar
toolFile = addToolBar("File");
toolFile->addAction(openAct);
toolFile->addAction(exitAct);
[...]
}