Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Qt signal

 

Qt signals are signals used by the Qt library and the IDE Qt Creator.

 

Always seperate classes with Qt signals/slots in a header (.h) file and an implementation (.cpp) file. If not, this will result in the link error undefined reference to 'vtable for MyClass'.

 

Below, a full example is shown using Qt signals.

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppSignal.pro

 

#-------------------------------------------------
#
# Project created by QtCreator 2010-12-29T13:23:42
#
#-------------------------------------------------
QT       += core
QT       -= gui
TARGET = CppSignal
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
    emitter.cpp \
    receiver.cpp
HEADERS += \
    emitter.h \
    receiver.h

 

 

 

 

 

emitter.cpp

 

#include <iostream>
#include "emitter.h"

Emitter::Emitter(QObject *parent) :
    QObject(parent)
{
}

void Emitter::DoEmit()
{
  std::clog << "Emitter: emitting signal\n";
  emit signal_emit();
}

 

 

 

 

 

emitter.h

 

#ifndef EMITTER_H
#define EMITTER_H

#include <QObject>

class Emitter : public QObject
{
  Q_OBJECT
public:
  explicit Emitter(QObject *parent = 0);
  void DoEmit();

signals:
  void signal_emit();

public slots:

};

#endif // EMITTER_H

 

 

 

 

 

main.cpp

 

#include <QtCore/QCoreApplication>
#include "emitter.h"
#include "receiver.h"

int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);
  Emitter e;
  Receiver r;
  QObject::connect(&e,SIGNAL(signal_emit()),&r,SLOT(OnReceive()));
  e.DoEmit();
  return a.exec();
}

 

 

 

 

 

receiver.cpp

 

#include <iostream>
#include "receiver.h"

Receiver::Receiver(QObject *parent) :
    QObject(parent)
{

}

void Receiver::OnReceive()
{
  std::clog << "Receiver: received signal\n";
}


 

 

 

 

 

receiver.h

 

#ifndef RECEIVER_H
#define RECEIVER_H

#include <QObject>

class Receiver : public QObject
{
  Q_OBJECT
public:
  explicit Receiver(QObject *parent = 0);

signals:

public slots:
  void OnReceive();
};

#endif // RECEIVER_H

 

 

 

 

 

Signal pages

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict