Qt for beginners Signals and slots 2: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Convert ExpressionEngine links)
(Merged)
Line 1: Line 1:
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
[[Category:Delete]]
 
{{WarningBox|text=Merged into [[Qt for Beginners]]}}
[toc align_right="yes" depth="3"]
[[Category:Qt_for_beginners]]
[[Category:Tutorial]]
[[Category:HowTo]]
 
= Qt for beginners — Signals and slots 2 =
 
[[Qt_for_beginners_Signals_and_slots|<<< Signals and slots]] | [[Qt_for_beginners|Summary]] | [[Qt_for_beginners_Exercise_1_basis|Exercise 1 : basis >>>]]
 
'''''Note:''' Unfortunately, the images are no longer available. See the official [http://doc.qt.io/qt-5/gettingstartedqt.html Getting Started with Qt Widgets] page for an alternative tutorial.''
 
This chapter covers the second part of signals and slots : implementing custom signals and slots.
 
Creating custom slots and signals is really simple. Slots are like normal methods, but with small decorations around. While signals needs little to no implementation at all.
 
== Creating custom signals and slots ==
 
Creating custom signals and slots is very simple. It is described by the following checklist
 
* add '''Q_OBJECT''' macro
* add '''signals''' section, and write signals prototypes.
* add '''public slots''' or '''protected slots''' or '''private slots''' sections, and write slots prototypes.
* implement slots as normal methods.
* establish connections.
 
=== Creating custom slots ===
 
In order to implement a slot, we first need to make the class be able to send signals and have slots (see previous chapter). This is done by setting the '''Q_OBJECT''' macro in the class declaration (often in the header).
 
After that, a slot should be declared in the corresponding section, and implemented as a normal method.
 
Finally, slots are connected to signals.
 
=== Creating signals ===
 
As for slots, we first need to add the '''Q_OBJECT''' macro.
 
Signals should also be declared in the ''signals'' section, and there is no need for them to be implemented.
 
They are emitted using the '''emit''' keyword :
 
<code>
emit mySignal();
</code>
 
Note that in order to send signals that have parameters, you have to pass them in the signal emission
 
<code>
emit mySignal(firstParameter, secondParameter …);
</code>
 
== Example ==
 
=== Creating custom slots ===
 
Let's start with our window with the button :
 
''window.h''
<code>
#ifndef WINDOW_H
#define WINDOW_H
 
#include <QWidget>
 
class QPushButton;
class Window : public QWidget
{
public:
explicit Window(QWidget *parent = 0);
private:
QPushButton *m_button;
};
 
#endif // WINDOW_H
</code>
 
''window.cpp''
<code>
#include "window.h"
 
#include <QPushButton>
 
Window::Window(QWidget *parent) :
QWidget(parent)
{
// Set size of the window
setFixedSize(100, 50);
 
// Create and position the button
m_button = new QPushButton("Hello World", this);
m_button->setGeometry(10, 10, 80, 30);
}
</code>
 
We might want to remove our previous connection that makes the application quit while clicking on the button. Now, we want that, when clicking on the button, the text is changed. More precisely, we want that the button can be ''checked'', and that, when checked, it displays "checked", and when unchecked, it restores "Hello World".
 
QPushButton does not implement such a specific slot, so we have to implement it on our own. As stated previously, we have to add the '''Q_OBJECT''' macro.
 
<code>
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
private:
QPushButton *m_button;
};
</code>
 
We also add our custom slot. Since we are trying to react from the button being checked, and since the corresponding signal is
 
<code>
void QPushButton::clicked(bool checked)
</code>
 
we might implement a slot that has this signature :
 
<code>
void Window::slotButtonClicked(bool checked);
</code>
 
Most of the time, by convention, we implement private and protected slots by prefixing them with "slot". Here, we are not interested in exposing this slot as a public function, we can make it private. The new header is then
 
''window.h''
<code>
#ifndef WINDOW_H
#define WINDOW_H
 
#include <QWidget>
 
class QPushButton;
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
private slots:
void slotButtonClicked(bool checked);
private:
QPushButton *m_button;
};
 
#endif // WINDOW_H
</code>
 
The implementation of this slot is
 
<code>
void Window::slotButtonClicked(bool checked)
{
if (checked) {
m_button->setText("Checked");
} else {
m_button->setText("Hello World");
}
}
</code>
 
We need to make the button checkable, and establish the connection, we have to add this code in the constructor :
 
<code>
m_button->setCheckable(true);
 
connect(m_button, SIGNAL (clicked(bool)), this, SLOT (slotButtonClicked(bool)));
</code>
 
The resulting code is then
 
''window.cpp''
 
<code>
#include "window.h"
 
#include <QPushButton>
 
Window::Window(QWidget *parent) :
QWidget(parent)
{
// Set size of the window
setFixedSize(100, 50);
 
// Create and position the button
m_button = new QPushButton("Hello World", this);
m_button->setGeometry(10, 10, 80, 30);
m_button->setCheckable(true);
 
connect(m_button, SIGNAL (clicked(bool)), this, SLOT (slotButtonClicked(bool)));
}
 
void Window::slotButtonClicked(bool checked)
{
if (checked) {
m_button->setText("Checked");
} else {
m_button->setText("Hello World");
}
}
</code>
 
And we should get this as a result
 
[[Image:http://farm9.staticflickr.com/8167/7514610590_2a4e342dc4_m.jpg|Custom slot]]
 
== Emitting custom signals ==
 
Based on the previous example, we want to close the application if the button is clicked (checked or unchecked) 10 times. We first need to implement a counter that will count the number of clicks. These modifications implement it
 
<code>
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
private slots:
void slotButtonClicked(bool checked);
private:
int m_counter;
QPushButton *m_button;
};
</code>
 
and
 
<code>
Window::Window(QWidget *parent) :
QWidget(parent)
{
// Set size of the window
setFixedSize(100, 50);
 
// Create and position the button
m_button = new QPushButton("Hello World", this);
m_button->setGeometry(10, 10, 80, 30);
m_button->setCheckable(true);
 
// Set the counter to 0
m_counter = 0;
 
connect(m_button, SIGNAL (clicked(bool)), this, SLOT (slotButtonClicked(bool)));
}
 
void Window::slotButtonClicked(bool checked)
{
if (checked) {
m_button->setText("Checked");
} else {
m_button->setText("Hello World");
}
 
m_counter '''';
}
</code>
 
Now, we have to create a custom signal that is used to notify other components, that the counter has reached 10. In order to declare a signal, we have to add a <code>signals</code> section in the header. We might also declare a signal with the following signature
 
<code>
void Window::counterReached()
</code>
 
The header class is then declared as followed
 
<code>
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
signals:
void counterReached();
private slots:
void slotButtonClicked(bool checked);
private:
int m_counter;
QPushButton *m_button;
};
</code>
 
Even if the signal is declared as a method, there is no need to implement it. The meta-object compiler is used to do this.
 
Now we need to emit the signal when the counter reaches 10. It is simply done in the slot
 
<code>
void Window::slotButtonClicked(bool checked)
{
if (checked) {
m_button->setText("Checked");
} else {
m_button->setText("Hello World");
}
 
m_counter '''';
if (m_counter == 10) {
emit counterReached();
}
}
</code>
 
We need to write the keyword '''emit''' to send the signal.
 
Connecting the newly created signal to the <code>quit</code> slot is done as usual
 
<code>
connect(this, SIGNAL (counterReached()), QApplication::instance(), SLOT (quit()));
</code>
 
The final code is
 
''window.h''
<code>
#ifndef WINDOW_H
#define WINDOW_H
 
#include <QWidget>
 
class QPushButton;
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
signals:
void counterReached();
private slots:
void slotButtonClicked(bool checked);
private:
int m_counter;
QPushButton *m_button;
};
 
#endif // WINDOW_H
</code>
 
''window.cpp''
<code>
#include "window.h"
 
#include <QPushButton>
#include <QApplication>
 
Window::Window(QWidget *parent) :
QWidget(parent)
{
// Set size of the window
setFixedSize(100, 50);
 
// Create and position the button
m_button = new QPushButton("Hello World", this);
m_button->setGeometry(10, 10, 80, 30);
m_button->setCheckable(true);
 
// Set the counter to 0
m_counter = 0;
 
connect(m_button, SIGNAL (clicked(bool)), this, SLOT (slotButtonClicked(bool)));
connect(this, SIGNAL (counterReached()), QApplication::instance(), SLOT (quit()));
}
 
void Window::slotButtonClicked(bool checked)
{
if (checked) {
m_button->setText("Checked");
} else {
m_button->setText("Hello World");
}
 
m_counter '''';
if (m_counter == 10) {
emit counterReached();
}
}
</code>
 
And you can try and check that after clicking the button ten times, the application will quit.
 
== Troubleshooting ==
 
While compiling your program, especially when you are adding the macro Q_OBJECT, you might have this compilation error.
 
<code>
main.cpp:(.text._ZN6WindowD2Ev[_ZN6WindowD5Ev]+0x3): undefined reference to `vtable for Window'
</code>
 
This is because of the meta-object compiler not being run on a class that should have meta-object. You should '''rerun qmake''', by doing Build > Run qmake.

Revision as of 20:47, 8 March 2015

Merged into Qt for Beginners