(C++) How to add an Event?

February 24, 2017 · View on GitHub

 

 

 

 

 

(C++) Qt How to add an Event?

 

How to add an Event? is a QT FAQ, especially for people with a C++ Builder background (like me): in C++ Builder the following steps were done for you automatically.

 

To add an Event (in Qt these are called 'slots'), three steps must be takes:

  1. Declare the Event/slot
  2. Define the Event/slot
  3. Connect a signal with the Event/slot

 

At the bottom of this page, a complete Qt Creator project can be downloaded.

 

 

 

 

Step 1: Declare the Event/slot

 

The Event/slot must be declared in the dialog's header file. In the example below the slot 'MyEvent' is declared. All other code is default-created by Qt Creator.

 


#ifndef DIALOG_H #define DIALOG_H #include <QDialog> namespace Ui {   class Dialog; } class Dialog : public QDialog {   Q_OBJECT public:   explicit Dialog(QWidget *parent = 0);   ~Dialog(); protected:   void changeEvent(QEvent *e); private:   Ui::Dialog *ui; private slots:   void MyEvent(); }; #endif // DIALOG_H

 

 

 

 

 

Step 2: Define the Event/slot

 

The Event/slot must be defined in the dialog's implementation file. In the example below the slot 'MyEvent' is defined to changed the dialog's title. All other code is default-created by Qt Creator.

 


#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) :     QDialog(parent),     ui(new Ui::Dialog) {     ui->setupUi(this); } Dialog::~Dialog() {     delete ui; } void Dialog::changeEvent(QEvent *e) {     QDialog::changeEvent(e);     switch (e->type()) {     case QEvent::LanguageChange:         ui->retranslateUi(this);         break;     default:         break;     } } void Dialog::MyEvent() {   this->setWindowTitle("MyEvent"); }

 

 

 

 

 

Step 3: Connect a signal with the Event/slot

 

Now that the Event/slot is declared, it must be specified what triggers its call. In Qt, Event/slots are triggered by a signal. In the example below the slot 'MyEvent' is set to be triggered (that is: connected) to the signal 'accepted()'. Note that this is a nearly-useless trigger: better would be something like a QPushButton's clicked() signal.

 


#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) :     QDialog(parent),     ui(new Ui::Dialog) {     ui->setupUi(this);     QObject::connect(this,SIGNAL(accepted()),this,SLOT(MyEvent())); } Dialog::~Dialog() {     delete ui; } void Dialog::changeEvent(QEvent *e) {     QDialog::changeEvent(e);     switch (e->type()) {     case QEvent::LanguageChange:         ui->retranslateUi(this);         break;     default:         break;     } } void Dialog::MyEvent() {   this->setWindowTitle("MyEvent"); }

 

 

 

 

 

About this example

 

Operating system: Ubuntu

IDE: Qt Creator 2.0.0

Project type: Qt4 GUI Application

Compiler: G++ 4.4.1

Libraries used:

  • Qt: version 4.7.0 (32 bit)