Events and signals in Qt4
In this part of the Qt4 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 it's 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, 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. Trolltech has introduced 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. A slot 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.
#ifndef CLICK_H
#define CLICK_H
#include <QWidget>
class Click : public QWidget
{
public:
Click(QWidget *parent = 0);
};
#endif
Header file.
#include "click.h"
#include <QPushButton>
#include <QApplication>
Click::Click(QWidget *parent)
: QWidget(parent)
{
QPushButton *quit = new QPushButton("Quit", this);
quit->setGeometry(50, 40, 75, 30);
connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
}
We display a QPushButton on the window.
connect(quit, SIGNAL(clicked()), qApp, SLOT(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.
#include "click.h"
#include <QDesktopWidget>
#include <QApplication>
void center(QWidget &widget)
{
int x, y;
int screenWidth;
int screenHeight;
int WIDTH = 250;
int HEIGHT = 150;
QDesktopWidget *desktop = QApplication::desktop();
screenWidth = desktop->width();
screenHeight = desktop->height();
x = (screenWidth - WIDTH) / 2;
y = (screenHeight - HEIGHT) / 2;
widget.setGeometry(x, y, WIDTH, HEIGHT);
widget.setFixedSize(WIDTH, HEIGHT);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Click window;
window.setWindowTitle("Click");
window.show();
center(window);
return app.exec();
}
Main file.
KeyPress
In the following example, we will react to a key press.
#ifndef KEYPRESS_H
#define KEYPRESS_H
#include <QWidget>
class KeyPress : public QWidget
{
public:
KeyPress(QWidget *parent = 0);
protected:
void keyPressEvent(QKeyEvent * event);
};
#endif
Header file.
#include "keypress.h"
#include <QApplication>
#include <QKeyEvent>
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 *event)
{
if (event->key() == Qt::Key_Escape) {
qApp->quit();
}
}
One of the ways of working with events in Qt4 programming library 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.
#include "keypress.h"
#include <QDesktopWidget>
#include <QApplication>
void center(QWidget &widget)
{
int x, y;
int screenWidth;
int screenHeight;
int WIDTH = 250;
int HEIGHT = 150;
QDesktopWidget *desktop = QApplication::desktop();
screenWidth = desktop->width();
screenHeight = desktop->height();
x = (screenWidth - WIDTH) / 2;
y = (screenHeight - HEIGHT) / 2;
widget.setGeometry(x, y, WIDTH, HEIGHT);
widget.setFixedSize(WIDTH, HEIGHT);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
KeyPress window;
window.setWindowTitle("Key press");
window.show();
center(window);
return app.exec();
}
Main file.
QMoveEvent
The QMoveEvent class contains event parameters for move events. Move events are sent to widgets that have been moved.
#ifndef MOVE_H
#define MOVE_H
#include <QMainWindow≫
class Move : public QWidget
{
public:
Move(QWidget *parent = 0);
protected:
void moveEvent(QMoveEvent *event);
};
#endif
Header file.
#include "move.h"
#include <QMoveEvent>
Move::Move(QWidget *parent)
: QWidget(parent)
{
}
void Move::moveEvent(QMoveEvent *event)
{
int x = event->pos().x();
int y = event->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 window and set those values to the title of the window.
int x = event->pos().x(); int y = event->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);
Set the text to the title of the window.
#include "move.h"
#include <QDesktopWidget>
#include <QApplication>
void center(QWidget &widget)
{
int x, y;
int screenWidth;
int screenHeight;
int WIDTH = 250;
int HEIGHT = 150;
QDesktopWidget *desktop = QApplication::desktop();
screenWidth = desktop->width();
screenHeight = desktop->height();
x = (screenWidth - WIDTH) / 2;
y = (screenHeight - HEIGHT) / 2;
widget.setGeometry(x, y, WIDTH, HEIGHT);
widget.setFixedSize(WIDTH, HEIGHT);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Move window;
window.setWindowTitle("Move");
window.show();
center(window);
return app.exec();
}
Main file.
Disconnecting an signal
A signal can be disconnected from the slot. The next example will show, how we can accomplish this.
#ifndef DISCONNECT_H
#define DISCONNECT_H
#include <QWidget>
#include <QPushButton>
class Disconnect : public QWidget
{
Q_OBJECT
public:
Disconnect(QWidget *parent = 0);
private slots:
void onClick();
void onCheck(int);
private:
QPushButton *click;
};
#endif
In the header file, we have declared two slots. The slots is not a C++ keyword. It is a Qt4 programming library 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.
#include "disconnect.h"
#include <QTextStream>
#include <QCheckBox>
Disconnect::Disconnect(QWidget *parent)
: QWidget(parent)
{
click = new QPushButton("Click", this);
click->setGeometry(50, 40, 75, 30);
QCheckBox *cb = new QCheckBox("Connect", this);
cb->setCheckState(Qt::Checked);
cb->move(150, 40);
connect(click, SIGNAL(clicked()),
this, SLOT(onClick()));
connect(cb, SIGNAL(stateChanged(int)),
this, SLOT(onCheck(int)));
}
void Disconnect::onClick()
{
QTextStream out(stdout);
out << "Button clicked\n";
}
void Disconnect::onCheck(int state)
{
if (state == Qt::Checked) {
connect(click, SIGNAL(clicked()),
this, SLOT(onClick()));
} else {
click->disconnect(SIGNAL(clicked()));
}
}
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(click, SIGNAL(clicked()),
this, SLOT(onClick()));
connect(cb, SIGNAL(stateChanged(int)),
this, SLOT(onCheck(int)));
Here we connect signals to our user defined slots.
void Disconnect::onClick()
{
QTextStream out(stdout);
out << "Button clicked\n";
}
If we click on the click button, we send "Button clicked" text to the terminal window.
void Disconnect::onCheck(int state)
{
if (state == Qt::Checked) {
connect(click, SIGNAL(clicked()),
this, SLOT(onClick()));
} else {
click->disconnect(SIGNAL(clicked()));
}
}
Inside the onCheck() slot, we connect/disconnect an onClick() slot from the click button.
#include "disconnect.h"
#include <QDesktopWidget>
#include <QApplication>
void center(QWidget &widget)
{
int x, y;
int screenWidth;
int screenHeight;
int WIDTH = 250;
int HEIGHT = 150;
QDesktopWidget *desktop = QApplication::desktop();
screenWidth = desktop->width();
screenHeight = desktop->height();
x = (screenWidth - WIDTH) / 2;
y = (screenHeight - HEIGHT) / 2;
widget.setGeometry(x, y, WIDTH, HEIGHT);
widget.setFixedSize(WIDTH, HEIGHT);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Disconnect window;
window.setWindowTitle("Disconnect");
window.show();
center(window);
return app.exec();
}
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.
#ifndef TIMER_H
#define TIMER_H
#include <QWidget>
#include <QLabel>
class Timer : public QWidget
{
public:
Timer(QWidget *parent = 0);
protected:
void timerEvent(QTimerEvent *event);
private:
QLabel *label;
};
#endif
Header file.
#include "timer.h"
#include <QTime>
Timer::Timer(QWidget *parent)
: QWidget(parent)
{
label = new QLabel("", this);
label->move(50, 50);
QTime qtime = QTime::currentTime();
QString stime = qtime.toString(Qt::LocalDate);
label->setText(stime);
startTimer(1000);
}
void Timer::timerEvent(QTimerEvent *event)
{
QTime qtime = QTime::currentTime();
QString stime = qtime.toString(Qt::LocalDate);
label->setText(stime);
}
In our example, we display a current local time on the window.
label = new QLabel("", this);
label->move(50, 50);
To display a time, we use a label widget.
QTime qtime = QTime::currentTime(); QString stime = qtime.toString(Qt::LocalDate); label->setText(stime);
Here we determine the current local time. We set it to the label widget.
startTimer(1000);
We start the timer. Every 1000ms a timer event is generated.
void Timer::timerEvent(QTimerEvent *event)
{
QTime qtime = QTime::currentTime();
QString stime = qtime.toString(Qt::LocalDate);
label->setText(stime);
}
To work with timer events, we must reimplement the timerEvent() method.
#include "timer.h"
#include <QDesktopWidget>
#include <QApplication>
void center(QWidget &widget)
{
int x, y;
int screenWidth;
int screenHeight;
int WIDTH = 250;
int HEIGHT = 150;
QDesktopWidget *desktop = QApplication::desktop();
screenWidth = desktop->width();
screenHeight = desktop->height();
x = (screenWidth - WIDTH) / 2;
y = (screenHeight - HEIGHT) / 2;
widget.setGeometry(x, y, WIDTH, HEIGHT);
widget.setFixedSize(WIDTH, HEIGHT);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Timer window;
window.setWindowTitle("Timer");
window.show();
center(window);
return app.exec();
}
Main file.
This chapter was dedicated to events and signals in Qt4.