- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Events and signals in Qt5
In this part of the Qt5 C++ programming tutorial we talk about events and signals.
Events are an important part in any GUI program. All GUI applications are event-driven. An application reacts to different event types which are generated during its life. Events are generated mainly by the user of an application. But they can be generated by other means as well, e.g. Internet connection, window manager, or a timer. In the event model, there are three participants:
- event source
- event object
- event target
The event source is the object whose state changes. It generates Events. The event object (Event) encapsulates the state changes in the event source. The event target is the object that wants to be notified. Event source object delegates the task of handling an event to the event target.
When we call the application's exec()
method, the application enters the main loop. The main loop fetches events and sends them to the objects. Qt has a unique signal and slot mechanism. This signal and slot mechanism is an extension to the C++ programming language.
Signals and slots are used for communication between objects. A signal is emitted when a particular event occurs. A slot is a normal C++ method; it is called when a signal connected to it is emitted.
Click
The first example shows a very simple event handling example. We have one push button. By clicking on the push button, we terminate the application.
click.h
#pragma once #include <QWidget> class Click : public QWidget { public: Click(QWidget *parent = 0); };
This is the header file.
click.cpp
#include <QPushButton> #include <QApplication> #include <QHBoxLayout> #include "click.h" Click::Click(QWidget *parent) : QWidget(parent) { QHBoxLayout *hbox = new QHBoxLayout(this); hbox->setSpacing(5); QPushButton *quitBtn = new QPushButton("Quit", this); hbox->addWidget(quitBtn, 0, Qt::AlignLeft | Qt::AlignTop); connect(quitBtn, &QPushButton::clicked, qApp, &QApplication::quit); }
We display a QPushButton
on the window.
connect(quitBtn, &QPushButton::clicked, qApp, &QApplication::quit);
The connect()
method connects a signal to the slot. When we click on the Quit button, the clicked
signal is generated. The qApp
is a global pointer to the application object. It is defined in the <QApplication>
header file. The quit()
method is called when the clicked signal is emitted.
main.cpp
#include <QApplication> #include "click.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Click window; window.resize(250, 150); window.setWindowTitle("Click"); window.show(); return app.exec(); }
This is the main file.

KeyPress
In the following example, we react to a key press.
keypress.h
#pragma once #include <QWidget> class KeyPress : public QWidget { public: KeyPress(QWidget *parent = 0); protected: void keyPressEvent(QKeyEvent * e); };
This is the keypress.h
header file.
keypress.cpp
#include <QApplication> #include <QKeyEvent> #include "keypress.h" KeyPress::KeyPress(QWidget *parent) : QWidget(parent) { } void KeyPress::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) { qApp->quit(); } }
The application terminates if we press the Escape key.
void KeyPress::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) { qApp->quit(); } }
One of the ways of working with events in Qt5 is to reimplement an event handler. The QKeyEvent
is an event object, which holds information about what has happened. In our case, we use the event object to determine which key was actually pressed.
main.cpp
#include <QApplication> #include "keypress.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); KeyPress window; window.resize(250, 150); window.setWindowTitle("Key press"); window.show(); return app.exec(); }
This is the main file.
QMoveEvent
The QMoveEvent
class contains event parameters for move events. Move events are sent to widgets that have been moved.
move.h
#pragma once #include <QMainWindow> class Move : public QWidget { Q_OBJECT public: Move(QWidget *parent = 0); protected: void moveEvent(QMoveEvent *e); };
This is the move.h
header file.
move.cpp
#include <QMoveEvent> #include "move.h" Move::Move(QWidget *parent) : QWidget(parent) { } void Move::moveEvent(QMoveEvent *e) { int x = e->pos().x(); int y = e->pos().y(); QString text = QString::number(x) + "," + QString::number(y); setWindowTitle(text); }
In our code programming example, we react to a move event. We determine the current x, y coordinates of the upper left corner of the client area of the window and set those values to the title of the window.
int x = e->pos().x(); int y = e->pos().y();
We use the QMoveEvent
object to determine the x
, y
values.
QString text = QString::number(x) + "," + QString::number(y);
We convert the integer values to strings.
setWindowTitle(text);
The setWindowTitle()
method sets the text to the title of the window.
main.cpp
#include <QApplication> #include "move.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Move window; window.resize(250, 150); window.setWindowTitle("Move"); window.show(); return app.exec(); }
This is the main file.

Disconnecting a signal
A signal can be disconnected from the slot. The next example shows how we can accomplish this.
disconnect.h
#pragma once #include <QWidget> #include <QPushButton> class Disconnect : public QWidget { Q_OBJECT public: Disconnect(QWidget *parent = 0); private slots: void onClick(); void onCheck(int); private: QPushButton *clickBtn; };
In the header file, we have declared two slots. The slots
is not a C++ keyword, it is a Qt5 extension. These extensions are handled by the preprocessor, before the code is compiled. When we use signals and slots in our classes, we must provide a Q_OBJECT
macro at the beginnig of the class definition. Otherwise, the preprocessor would complain.
disconnect.cpp
#include <QTextStream> #include <QCheckBox> #include <QHBoxLayout> #include "disconnect.h" Disconnect::Disconnect(QWidget *parent) : QWidget(parent) { QHBoxLayout *hbox = new QHBoxLayout(this); hbox->setSpacing(5); clickBtn = new QPushButton("Click", this); hbox->addWidget(clickBtn, 0, Qt::AlignLeft | Qt::AlignTop); QCheckBox *cb = new QCheckBox("Connect", this); cb->setCheckState(Qt::Checked); hbox->addWidget(cb, 0, Qt::AlignLeft | Qt::AlignTop); connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick); connect(cb, &QCheckBox::stateChanged, this, &Disconnect::onCheck); } void Disconnect::onClick() { QTextStream out(stdout); out << "Button clicked" << endl; } void Disconnect::onCheck(int state) { if (state == Qt::Checked) { connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick); } else { disconnect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick); } }
In our example, we have a button and a check box. The check box connects and disconnects a slot from the buttons clicked signal. This example must be executed from the command line.
connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick); connect(cb, &QCheckBox::stateChanged, this, &Disconnect::onCheck);
Here we connect signals to our user defined slots.
void Disconnect::onClick() { QTextStream out(stdout); out << "Button clicked" << endl; }
If we click on the Click button, we send the "Button clicked" text to the terminal window.
void Disconnect::onCheck(int state) { if (state == Qt::Checked) { connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick); } else { disconnect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick); } }
Inside the onCheck()
slot, we connect or disconnect the onClick()
slot from the Click button, depending on the received state.
main.cpp
#include <QApplication> #include "disconnect.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Disconnect window; window.resize(250, 150); window.setWindowTitle("Disconnect"); window.show(); return app.exec(); }
This is the main file.
Timer
A timer is used to implement single shot or repetitive tasks. A good example where we use a timer is a clock; each second we must update our label displaying the current time.
timer.h
#pragma once #include <QWidget> #include <QLabel> class Timer : public QWidget { public: Timer(QWidget *parent = 0); protected: void timerEvent(QTimerEvent *e); private: QLabel *label; };
This is the header file.
timer.cpp
#include "timer.h" #include <QHBoxLayout> #include <QTime> Timer::Timer(QWidget *parent) : QWidget(parent) { QHBoxLayout *hbox = new QHBoxLayout(this); hbox->setSpacing(5); label = new QLabel("", this); hbox->addWidget(label, 0, Qt::AlignLeft | Qt::AlignTop); QTime qtime = QTime::currentTime(); QString stime = qtime.toString(); label->setText(stime); startTimer(1000); } void Timer::timerEvent(QTimerEvent *e) { Q_UNUSED(e); QTime qtime = QTime::currentTime(); QString stime = qtime.toString(); label->setText(stime); }
In our example, we display a current local time on the window.
label = new QLabel("", this);
To display a time, we use a label widget.
QTime qtime = QTime::currentTime(); QString stime = qtime.toString(); label->setText(stime);
Here we determine the current local time. We set it to the label widget.
startTimer(1000);
We start the timer. Every 1000 ms a timer event is generated.
void Timer::timerEvent(QTimerEvent *e) { Q_UNUSED(e); QTime qtime = QTime::currentTime(); QString stime = qtime.toString(); label->setText(stime); }
To work with timer events, we must reimplement the timerEvent()
method.
main.cpp
#include <QApplication> #include "timer.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Timer window; window.resize(250, 150); window.setWindowTitle("Timer"); window.show(); return app.exec(); }
This is the main file.

This chapter was dedicated to events and signals in Qt5.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论