9.3.2.  Connecting to slots

[ fromfile: eventloop.xml id: slots ]

In Example 9.6, we saw the following connections established:

QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));
qApp->connect(shoutButton, SIGNAL(clicked()), msgr, SLOT(shout()));

connect() is actually a static member of QObject and can be called with any QObject or, as we showed, by means of its class scope resolution operator. qApp is a global pointer that points to the currently running QApplication.

The second connect goes to a slot that we declared in Example 9.7.

Example 9.7. src/eventloop/messager.h

#ifndef MESSAGER_H
#define MESSAGER_H

#include <QObject>
#include <QString>
#include <QErrorMessage>

class Messager : public QObject {
    Q_OBJECT
 public:
    Messager (QString msg, QWidget* parent=0);

 public slots:
    void shout();

 private:
    QWidget* m_Parent;
    QErrorMessage* m_Message;
};

#endif


Declaring a member function to be a slot enables it to be connected to a signal so that it can be called passively in response to some event. For its definition, shown in Example 9.8, we have kept things quite simple: the shout() function simply pops up a message box on the screen.

Example 9.8. src/eventloop/messager.cpp

#include "messager.h"

Messager::Messager(QString msg, QWidget* parent)
        : m_Parent(parent) {
    m_Message = new QErrorMessage(parent);
    setObjectName(msg);
}

void Messager::shout() {
    m_Message->showMessage(objectName());
}