QT signal error: "this" is unavailable for static member function - qt

I'm working at a socket class for my application that will introduce me in QT framework. When I try to build I get this error: 'this' is unavailable for static member functions.
This is my class .h and .cpp
#pragma once
#include <QObject>
class QTcpSocket;
namespace Ps{
class InstSocket : public QObject
{
Q_OBJECT
public:
InstSocket(QObject *parent=0);
bool Connect();
bool isOpen();
void Disconnect();
//Geters
QString GetHostName() const {return m_hostName;}
quint16 GetPort() const {return m_port;}
//seters
void SetHostName(const QString& value);
void SetPort(quint16 value);
void SetLongWaitMs(int value){m_longWaitMs = value;}
void SetShortWaitMs(int value){m_shortWaitMs = value;}
void WriteData(const QString &data) const;
~InstSocket();
QString ReadData() const;
signals:
static void NotifyConnected();
static void NotifyDisconnected();
private slots:
void onConnected();
void onDisconnected();
private:
//this holds a reference to QtcpSocket
QTcpSocket& m_socket;
QString m_hostName;
quint16 m_port;
int m_shortWaitMs;
int m_longWaitMs;
explicit InstSocket(const InstSocket& rhs) = delete;
InstSocket& operator= (const InstSocket& rhs) = delete;
};
}
and the cpp:
#include "instsocket.h"
#include "QTcpSocket"
#include "QDebug"
#include "utils.h"
namespace Ps
{
InstSocket::InstSocket(QObject *parent) :
QObject(parent),
m_socket(*new QTcpSocket(this)),
m_hostName(""),
m_port(0),
m_shortWaitMs(0),
m_longWaitMs(0)
{
/* my signals are wired to the undelying socket signals, the signal connected is triggered, when a conection
* is established. This will be wired to onConnected and Disconnected slots*/
connect(&m_socket, &QTcpSocket::connected, this, &InstSocket::onConnected);
connect(&m_socket, &QTcpSocket::disconnected, this, &InstSocket::onDisconnected);
}
bool InstSocket::Connect()
{
qDebug() << "attempting to connect to "<< m_hostName << "on port" << m_port << "with wait time: "<<m_longWaitMs;
m_socket.connectToHost(m_hostName, m_port, QTcpSocket::ReadWrite);
return m_socket.waitForConnected(m_longWaitMs);
}
bool InstSocket::isOpen()
{
return m_socket.isOpen();
}
void InstSocket::Disconnect()
{
if(!isOpen()) return;
m_socket.disconnectFromHost();
}
void InstSocket::onConnected()
{
emit NotifyConnected();
}
void InstSocket::onDisconnected()
{
emit NotifyDisconnected();
}
void InstSocket::SetHostName(const QString &value)
{
m_hostName = value;
}
void InstSocket::SetPort(quint16 value)
{
m_port = value;
}
void InstSocket::WriteData(const QString &data) const
{
/*support for writeing to socket. The write metod of the socket will return the number of bites writen*/
int bytes_written = m_socket.write(qPrintable(data));
qDebug() << "Bytes written: "<<bytes_written;
}
QString InstSocket::ReadData() const
{
if(!m_socket.isReadable())
{
return "ERROR: Socket is unreadable.";
}
QString result;
//until the socket reports there is no data available
while(!m_socket.atEnd())
{
result.append(m_socket.readAll());
/*since typically a PC would be much faster at reading than an instrument might be at writing
* instrument must have a chance to queue up more data in case the message it's sending us is long.*/
m_socket.waitForReadyRead(m_shortWaitMs);
}
return result;
}
InstSocket::~InstSocket()
{
Utils::DestructorMsg(this);
}
}
and this is the error:
Qt Projects\build-Vfp-Desktop_Qt_5_7_0_MSVC2015_64bit-Debug\debug\moc_instsocket.cpp:-1: In static member function 'static void Ps::InstSocket::NotifyConnected()':
error: 'this' is unavailable for static member functions
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); In static member function 'static void Ps::InstSocket::NotifyDisconnected()':
error: 'this' is unavailable for static member functions
QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR);
When I clicked on them, QT creator took me to moc_instsocket.cpp (that is in build folder and poit to this:
// SIGNAL 0
void Ps::InstSocket::NotifyConnected()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
// SIGNAL 1
void Ps::InstSocket::NotifyDisconnected()
{
QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR);
}
I can't figure out what to do althought I checked all the code several times. There is no need to know about utils class since there are just some debug messages. Did anyone know how to fix it?

What is the meaning of static signal? In Qt signals and slots are used on object level.
signals:
static void NotifyConnected();
static void NotifyDisconnected();
All classes that inherit from QObject or one of its subclasses (e.g., QWidget) can contain signals and slots. Signals are emitted by objects when they change their state in a way that may be interesting to other objects. This is all the object does to communicate. It does not know or care whether anything is receiving the signals it emits. This is true information encapsulation, and ensures that the object can be used as a software component. Signal Slots documentation

Related

QtRemoteObjects replicas being called for every single replica signal

I built a minimal source/replica direct connection QtRo system:
https://codeshare.io/29xj4V
What I would like to achieve is uniquely identify the message coming from the source to be a reply to the one sent from each of the replicas.
If rep1 sends "hello source, I'm rep1", I'd like the source to reply back "hello rep1 this is source". I would like to achieve the same with 3 replicas running at a very high and different rate. The issue is on every signal to the source the source replies back to all 3 replicas; the way i'm filtering this is by sending the "id" of the replica in text format then append that id back with the message to check for it inside the replica itself, if it's a match then it accepts the message, otherwise it discards it. Although this seems to be working, there's a big overhead here. My question would be: is there a better way to handle that instead of sending an identifier back and forth? thanks
The replicas receive the same signals, there is no way to filter that data from the source side. So the filtering must be done on the client's side, for this you can use an attribute that is the identifier and send that data as a new parameter in the signal instead of sending it within the message. So although there is a lot of calls the cost will be minimal since the if statement does not consume much time.
remoteminimal.rep
class RemoteMinimal
{
SIGNAL(sendData(const QString &, const QString &));
SLOT(void printData(const QString &));
SLOT(void process(const QString &, const QString &));
SLOT(void triggerSendData());
};
minimalsource.h
#ifndef MINIMALSOURCE_H
#define MINIMALSOURCE_H
#include "rep_remoteminimal_source.h"
#include <QObject>
class MinimalSource : public RemoteMinimalSource
{
Q_OBJECT
public:
MinimalSource(QObject *parent = nullptr);
~MinimalSource() override;
public slots:
void printData(const QString& data) override;
void process(const QString& data, const QString & id) override;
void triggerSendData() override;
private:
int m_global_server;
};
#endif // MINIMALSOURCE_H
minimalsource.cpp
#include "minimalsource.h"
MinimalSource::MinimalSource(QObject* parent):
RemoteMinimalSource (parent), m_global_server(0)
{
}
MinimalSource::~MinimalSource(){}
void MinimalSource::printData(const QString& data)
{
Q_UNUSED(data);
}
void MinimalSource::process(const QString& data, const QString &id)
{
m_global_server++;
emit sendData(data+":"+QString::number(m_global_server), id);
}
void MinimalSource::triggerSendData()
{
}
objects.h
#ifndef OBJECTS_H
#define OBJECTS_H
#include <QObject>
#include "rep_remoteminimal_replica.h"
class QTimer;
class Objects: public QObject
{
Q_OBJECT
Q_PROPERTY(QString id READ id WRITE setId)
Q_PROPERTY(double rate READ rate WRITE setRate)
public:
explicit Objects(QSharedPointer<RemoteMinimalReplica> ptr);
~Objects();
double rate() const;
void setRate(double rate);
QString id() const;
void setId(const QString &id);
signals:
void sendData(const QString&, const QString &);
public slots:
void printData(const QString&, const QString &);
void process(const QString&);
void triggerSendData();
void run();
private:
int m_global_server;
QTimer *m_loop;
double m_rate;
QString m_id;
QSharedPointer<RemoteMinimalReplica> reptr;
};
#endif // OBJECTS_H
objects.cpp
#include "objects.h"
#include <QTimer>
#include <QDebug>
Objects::Objects(QSharedPointer<RemoteMinimalReplica> ptr): QObject (Q_NULLPTR),
m_global_server(0), reptr(ptr)
{
m_loop = new QTimer(this);
}
Objects::~Objects(){}
void Objects::printData(const QString& data, const QString& id)
{
if(id == m_id)
qDebug() << "[" << m_id << "]:" << data;
}
void Objects::process(const QString& data)
{
emit sendData(data+":processed", m_id);
}
void Objects::run()
{
connect(m_loop, &QTimer::timeout, this, &Objects::triggerSendData);
m_loop->setInterval(static_cast<int>(1000/m_rate));
m_loop->start();
}
QString Objects::id() const
{
return m_id;
}
void Objects::setId(const QString &id)
{
m_id = id;
}
double Objects::rate() const
{
return m_rate;
}
void Objects::setRate(double rate)
{
m_rate = rate;
}
void Objects::triggerSendData()
{
m_global_server++;
emit sendData(QString("test:%1:%2").arg(m_id).arg(m_global_server), m_id);
}
The complete example you find here

QObject::connect: Cannot queue arguments of type 'QModbusDevice::State'

I'm developing a multithreaded application, I need to instantiate n devices by modbus.
So I created a controller (ServiceSM) that instantiates N threads (ServiceSlots).
The devices are varied so I had to create "drivers" for each type of device, one of the drivers uses the QModbusClient class, so I created a controller to manage the device type.
schema
To test the operation of the state machine and connection to the device, I made an example code to run in a graphical interface.
I deleted some snippets of code that do not matter to make it easier to understand
In the MD4040driver class
When my code runs this section, the following messages appear.
If I instantiate the DeviceDriver class in the graphical interface, it works perfectly, the problem occurs when I instantiate it inside a thread.
when calls
modbusDevice->connectDevice()
MD4040drive::sm_conn() - try connect - this my message
Error:
QObject::connect: Cannot queue arguments of type
'QModbusDevice::State' (Make sure 'QModbusDevice::State' is registered
using qRegisterMetaType().)
QObject: Cannot create children for a parent that is in a different
thread. (Parent is QTcpSocket(0x24a6ce8), parent's thread is
ServiceSlots(0xea66488), current thread is QThread(0x2418a78)
QObject: Cannot create children for a parent that is in a different
thread. (Parent is QTcpSocket(0x24a6ce8), parent's thread is
ServiceSlots(0xea66488), current thread is QThread(0x2418a78)
void MD4040drive::sm_conn()
{
if (modbusDevice->state() != QModbusDevice::ConnectedState) {
modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->cfg.modbus.porta );
modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, this->cfg.modbus.ip);
modbusDevice->setTimeout( this->cfg.modbus.timeout );
modbusDevice->setNumberOfRetries(this->cfg.modbus.retries);
qDebug() << "MD4040drive::sm_conn() - try connect";
if (!modbusDevice->connectDevice()) {
qDebug() << "Erro: " << modbusDevice->errorString();
} else {
qDebug() << "Aguardando conexão...";
}
}
else{
//already connected...
this->getDados_NO_TH();
}
}
rest my code(parts)
devicedriverviewgui.h
devicedriverviewgui.cpp
class DeviceDriverViewGUI : public QDialog
{
Q_OBJECT
public:
explicit DeviceDriverViewGUI(QWidget *parent = 0);
~DeviceDriverViewGUI();
private slots:
void on_pbTry_clicked();
private:
Ui::DeviceDriverViewGUI *ui;
ServiceSlots *serviceSlot;
};
void DeviceDriverViewGUI::on_pbTry_clicked()
{
Equip equip_try = Equip();
serviceSlot = new ServiceSlots();
serviceSlot->setEquipamento(equip_try);
serviceSlot->start();
}
serviceslots.h
serviceslots.cpp
class ServiceSlots : public QThread
{
Q_OBJECT
public:
ServiceSlots();
void run();
private:
QTimer *timer;
DeviceDriver *device;
private slots:
void sm_getData();
void device_response(bool boEnd);
};
void ServiceSlots::run()
{
int e;
eventLoop = new QEventLoop();
timer = new QTimer();
connect(timer, SIGNAL(timeout()),this, SLOT(sm_controler()));
timer->start(TICK_SM_SLOT);
this->device = new DeviceDriver();
e = eventLoop->exec();
qDebug() << "Exit loop"<< e;
}
void ServiceSlots::sm_controler()
{
if(this->idleState){;}
else{
this->sm_getData();
this->idleState = true;
}
}
void ServiceSlots::sm_getData()
{
connect(device,SIGNAL(end(bool)),this,SLOT(device_response(bool)));
device->requestDeviceDriver(&this->equipamento,&this->next_date);
}
devicedriver.h
devicedriver.cpp
class DeviceDriver : public QObject
{
Q_OBJECT
public:
DeviceDriver();
void requestDeviceDriver(Equip *equip,QDateTime *date);
private:
//Drivers de dispositivos..
MD4040drive *md4040;
private slots:
//Request data to driver...
void request();
signals:
void end(bool boEnd);
};
void DeviceDriver::request()
{
connect(md4040,SIGNAL(end(bool)),this,SLOT(md4040_end(bool)));
this->md4040->requestMD4040drive(&this->equip,&this->date);
}
DeviceDriver::DeviceDriver(){
----
md4040 = new MD4040drive();
---
}
void DeviceDriver::requestDeviceDriver(Equip *equip, QDateTime *date){
this->equip = *equip;
this->date = *date;
this->request();
}
md4040drive.h
md4040drive.cpp
class MD4040drive : public QObject // QObject//public QObject QRunnable QThread
{
Q_OBJECT
public:
explicit MD4040drive(QObject *parent = 0);
~MD4040drive();
void requestMD4040drive(Equip *equip,QDateTime *date);
private:
void run();
QModbusClient *modbusDevice;
private slots:
void m_conn();
signals:
void end(bool boRun);
};
MD4040drive::MD4040drive(QObject *parent): QObject(parent)
{
modbusDevice = new QModbusTcpClient();
connect(modbusDevice, &QModbusClient::stateChanged,this, &MD4040drive::onStateChanged);
}
void MD4040drive::requestMD4040drive(Equip *equip, QDateTime *date)
{
this->equip = *equip;
this->date = *date;
this->run();
}
void MD4040drive::run()
{
this->sm_conn();
}
void MD4040drive::sm_conn()
{
if (modbusDevice->state() != QModbusDevice::ConnectedState) {
modbusDevice->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->cfg.modbus.porta );
modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, this->cfg.modbus.ip);
modbusDevice->setTimeout( this->cfg.modbus.timeout );
modbusDevice->setNumberOfRetries(this->cfg.modbus.retries);
qDebug() << "MD4040drive::sm_conn() - try connect";
if (!modbusDevice->connectDevice()) {
qDebug() << "Erro: " << modbusDevice->errorString();
} else {
qDebug() << "Aguardando conexão...";
}
}
else{
//already connected...
this->getDados_NO_TH();
}
}
There are a few problems:
You need to call qRegisterMetaType<QModbusDevice::State>() in main().
You need to maintain parent-child relationships between all objects that are potentially moved to other threads as a group.
The ServiceSlots and DeviceDriver classes seem to be unnecessary.
The ubiquitous this-> is non-idiomatic C++. Don't write this-> unless you need to disambiguate a member from a local variable.
Prefer to hold objects by value if they have the same lifetime as the parent object. Let the compiler generate memory management code for you!
Leverage C++11.
Fist of all, let's have a helper SafeThread class that provides us with a thread that is safely destructible at any time:
class SafeThread : public QThread {
Q_OBJECT
using QThread::run;
public:
using QThread::QThread;
~SafeThread() { quit(); wait(); }
};
The DeviceDriverViewGUI class can hold the drive and its thread by value:
class DeviceDriverViewGUI : public QDialog
{
Q_OBJECT
public:
explicit DeviceDriverViewGUI(QWidget *parent = nullptr);
private:
Ui::DeviceDriverViewGUI ui;
MD4040drive drive;
SafeThread driveThread{this};
Equip equipamento;
QDateTime nextDate;
Q_SLOT void on_pbTry_clicked();
};
Then, the pushbutton can be connected directly to the drive's thread context, and run the requestMD4040drive in the proper thread:
DeviceDriverViewGUI::DeviceDriverViewGUI(QWidget *parent) : QDialog(parent)
{
ui.setupUi(this);
// vvvvvv -- gives the thread context
connect(ui.pbTry, &QPushButton::clicked, &drive, [this]{
Q_ASSERT(QThread::currentThread() == drive.thread()); // ensured by the thread context
drive.requestMD4040drive(&equipamento, nextDate);
});
connect(&drive, &MD4040drive::end, this, [this](bool end){
//...
});
drive.moveToThread(&driveThread);
driveThread.start();
}
When done this way, you don't need any extraneous helper objects nor timers to queue requests. Qt handles all of it.
When passing Qt value classes to functions, pass them by const reference, not by pointer. The MD4040drive should look roughly as follows:
class MD4040drive : public QObject
{
Q_OBJECT
public:
explicit MD4040drive(QObject *parent = nullptr);
void requestMD4040drive(Equip *equip, const QDateTime &date);
Q_SIGNAL void end(bool boRun);
private:
Equip *equip = nullptr;
QDateTime date;
QModbusTcpClient modbusDevice{this};
Cfg cfg;
Q_SLOT void onStateChanged();
Q_SLOT void m_conn();
void sm_conn();
void getDados_NO_TH() {}
};
The implementation:
MD4040drive::MD4040drive(QObject *parent): QObject(parent)
{
connect(&modbusDevice, &QModbusClient::stateChanged,this, &MD4040drive::onStateChanged);
}
void MD4040drive::requestMD4040drive(Equip *equip, const QDateTime &date)
{
this->equip = equip;
this->date = date;
sm_conn();
}
void MD4040drive::sm_conn()
{
if (modbusDevice.state() != QModbusDevice::ConnectedState) {
modbusDevice.setConnectionParameter(QModbusDevice::NetworkPortParameter, cfg.modbus.porta );
modbusDevice.setConnectionParameter(QModbusDevice::NetworkAddressParameter, cfg.modbus.ip);
modbusDevice.setTimeout( this->cfg.modbus.timeout );
modbusDevice.setNumberOfRetries(this->cfg.modbus.retries);
qDebug() << "MD4040drive::sm_conn() - try connect";
if (!modbusDevice.connectDevice()) {
qDebug() << "Erro: " << modbusDevice.errorString();
} else {
qDebug() << "Aguardando conexão...";
}
}
else{
//already connected...
getDados_NO_TH();
}
}
The configuration class might look as follows - notice that the compiler will generate the necessary constructors and destructors for you:
struct Cfg {
struct Modbus {
int porta = 0;
QString ip = QStringLiteral("127.0.0.1");
int timeout = 1000;
int retries = 2;
} modbus;
};
Make sure 'QModbusDevice::State' is registered using qRegisterMetaType()
Means you need to call qRegisterMetaType<QModbusDevice::State>(); before connecting signal/slot that would pass this type of parameter between threads.
And/or add Q_DECLARE_METATYPE(QModbusDevice::State) macro at global scope (never understood clearly which one is actually needed, putting both works for sure...).
See this post for more details: Emitting signals with custom types does not work

How can I join a Thread running a function from the mainWindow class (Principal)?

I got this Error Message when I compile my project:
"Can not convert 'Principal::setValues' from type 'void*(Principal::)(void*)' to type 'void*()(void)' "
...
enter code here
void* Principal:: setValues(void*){
QString velocidadCARGA=QString::number(VelocidadCargador);
QString velocidadLAVA=QString::number(VelocidadLavado);
ui->Velocidad_Carga->setText(velocidadCARGA);
ui->Velocidad_Lavado->setText(velocidadLAVA);
ui->lbl_CantidadActual_Banda_Principal->setNum(botellasCargadas);
return NULL;
}
void Principal::on_Start_Cargador_clicked(){
pthread_t hilo3;
pthread_create(&hilo3,NULL,setValues,NULL);//error in this line.
pthread_join(hilo3,NULL);
}
Principal::setValues is a member function, so its type does not conform with a function type required by pthread_create.
To launch a member function in a thread you can declare some static method and pass this object into it:
class Principal
{
...
static void* setValuesThread(void *data);
...
}
void* Principal::setValuesThread(void *data)
{
Principal *self = reinterpret_cast<Principal*>(data);
self->setValues();
return NULL;
}
// your code
void Principal::setValues()
{
QString velocidadCARGA=QString::number(VelocidadCargador);
QString velocidadLAVA=QString::number(VelocidadLavado);
ui->Velocidad_Carga->setText(velocidadCARGA);
ui->Velocidad_Lavado->setText(velocidadLAVA);
ui->lbl_CantidadActual_Banda_Principal->setNum(botellasCargadas);
}
void Principal::on_Start_Cargador_clicked()
{
pthread_t hilo3;
pthread_create(&hilo3, NULL, Principal::setValuesThread, this);
pthread_join(hilo3,NULL);
}
But if Principal is a Qt widget (and I suppose it is), this code won't work because in Qt you can access widgets from the main thread only.
If you want to have some heavy calculations in a worker thread and then pass the results to your widget, you can use QThread and Qt signals/slots mechanism.
A simple example:
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QObject *parent = 0);
void run();
signals:
void dataReady(QString data);
}
void MyThread::run()
{
QString data = "Some data calculated in this worker thread";
emit dataReady(data);
}
class Principal
{
...
public slots:
void setData(QString data);
}
void Principal::setData(QString data)
{
ui->someLabel->setText(data);
}
void Principal::on_Start_Cargador_clicked()
{
MyThread *thread = new MyThread;
connect(thread, SIGNAL(dataReady(QString)), this, SLOT(setData(QString()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
Here is some related articles on Qt multithreading technologies:
http://doc.qt.io/qt-5/thread-basics.html
http://doc.qt.io/qt-5/threads-technologies.html

Extending QSettings to load / store Application settings

I'm trying to persist some application specific info in a settings file. Info like form size and position, the state of some check boxes on the main form etc. I trying to extend the QSettings class to do this.
This is what I have so far:
appsettings.h
class AppSettings : public QSettings
{
Q_OBJECT
public:
explicit AppSettings(QObject *parent = 0);
void load();
void save();
bool getLinkState();
bool getFullState();
void setLinkState(bool state);
void setFullState(bool state);
signals:
public slots:
private:
int mainTop;
int mainLeft;
int mainWidth;
int mainHeight;
bool cbFullState;
bool cbLinkState;
}
appsettings.cpp
#include "appsettings.h"
#include <QDebug>>
AppSettings::AppSettings(QObject *parent) :
QSettings(parent)
{
load();
}
void load(){
qDebug() << "appSettings load()"" ;
}
void save() {
qDebug() << "appSettings save()"" ;
}
bool getLinkState() {
return cbLinkState;
}
bool getFullState() {
return cbFullState;
}
void setLinkState(bool state)
{
if (state == cbLinkState) return;
cbLinkState = state;
save();
}
void setFullState(bool state)
{
if (state == cbFullState) return;
cbFullState = state;
save();
}
mainwindow.cpp
AppSettings *appSettings = AppSettings("MyOrgName", "MyAppName);
cbLink->setChecked( appSettings->getLinkState() );
I'm unsure how to:
1) create the object in the mainwindow such that the organsiation name and application name get passed through to QSettings that I've inherited from. I get a "no matching function" compile error on the first line in the mainwindow code above.
2) if I use the AppSettings class to store (cache) the info, how to create it only once and make it available from other windows and classes. For example, I may want to store the location of other windows as well as the main window.

How to test a QStateMachine?

I'm a bit confused about how to test a QStateMachine.
I have a project well organized with source code in one side and test code on the other side.
header
class Foo
{
signals:
void sigGoToStateOne();
void sigGoToStateTwo();
void sigGoToStateThree();
private:
QStateMachine *stateMachine;
QState *state1;
QState *state2;
void initStateMachine();
}
And in the source file
Foo::initStateMachine()
{
// constructors
state1->addTransition(this,SIGNAL(sigGoToStateTwo()),this->state2);
state2->addTransition(this,SIGNAL(sigGoToStateOne()),this->state1);
}
I would like to know if there is a beautiful way to test if my stateMachine is right. In other words, how my state machine reacts if I emit sigGoToStateThree() if I'm there, etc..
Solutions i see:
1 - Get the address of stateMachine (and eventually all other states) and test it (But i don't know how)
2 - Simulate signals (sigGoToStateX()) from a test file (Again, don't know if it's possible to emit signals of my class Foo in an other class)
My unique demand is I don't want to modify the core of my source file.
Thank's in advance.
In Qt 5, signals are always public methods. To make your code compatible with Qt 4, you can make the signals explicitly public like so:
class Foo {
public:
Q_SIGNAL void sigGoToStateOne();
...
}
Alternatively, you can keep arbitrary signal visibility, and declare a friend test class:
class Foo {
friend class FooTest;
...
}
Finally, you can create a test project where you use the Qt's test framework to test the Foo class's behavior. The code below works in both Qt 4 and Qt 5.
// main.cpp
#include <QCoreApplication>
#include <QStateMachine>
#include <QEventLoop>
#include <QtTest>
#include <QTimer>
class Waiter {
QTimer m_timer;
public:
Waiter() {}
Waiter(QObject * obj, const char * signal) {
m_timer.connect(obj, signal, SIGNAL(timeout()));
}
void stop() {
m_timer.stop();
QMetaObject::invokeMethod(&m_timer, "timeout");
}
void wait(int timeout = 5000) {
QEventLoop loop;
m_timer.start(timeout);
loop.connect(&m_timer, SIGNAL(timeout()), SLOT(quit()));
loop.exec();
}
};
class SignalWaiter : public QObject, public Waiter {
Q_OBJECT
int m_count;
Q_SLOT void triggered() {
++ m_count;
stop();
}
public:
SignalWaiter(QObject * obj, const char * signal) : m_count(0) {
connect(obj, signal, SLOT(triggered()), Qt::QueuedConnection);
}
int count() const { return m_count; }
};
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
typedef QSignalSpy SignalSpy;
#else
class SignalSpy : public QSignalSpy, public Waiter {
public:
SignalSpy(QObject * obj, const char * signal) :
QSignalSpy(obj, signal), Waiter(obj, signal) {}
};
#endif
class Foo : public QObject {
Q_OBJECT
friend class FooTest;
QStateMachine m_stateMachine;
QState m_state1;
QState m_state2;
Q_SIGNAL void sigGoToStateOne();
Q_SIGNAL void sigGoToStateTwo();
public:
explicit Foo(QObject * parent = 0) :
QObject(parent),
m_state1(&m_stateMachine),
m_state2(&m_stateMachine)
{
m_stateMachine.setInitialState(&m_state1);
m_state1.addTransition(this, SIGNAL(sigGoToStateTwo()), &m_state2);
m_state2.addTransition(this, SIGNAL(sigGoToStateOne()), &m_state1);
}
Q_SLOT void start() {
m_stateMachine.start();
}
};
class FooTest : public QObject {
Q_OBJECT
void call(QObject * obj, const char * method) {
QMetaObject::invokeMethod(obj, method, Qt::QueuedConnection);
}
Q_SLOT void test1() {
// Uses QSignalSpy
Foo foo;
SignalSpy state1(&foo.m_state1, SIGNAL(entered()));
SignalSpy state2(&foo.m_state2, SIGNAL(entered()));
call(&foo, "start");
state1.wait();
QCOMPARE(state1.count(), 1);
call(&foo, "sigGoToStateTwo");
state2.wait();
QCOMPARE(state2.count(), 1);
call(&foo, "sigGoToStateOne");
state1.wait();
QCOMPARE(state1.count(), 2);
}
Q_SLOT void test2() {
// Uses SignalWaiter
Foo foo;
SignalWaiter state1(&foo.m_state1, SIGNAL(entered()));
SignalWaiter state2(&foo.m_state2, SIGNAL(entered()));
foo.start();
state1.wait();
QCOMPARE(state1.count(), 1);
emit foo.sigGoToStateTwo();
state2.wait();
QCOMPARE(state2.count(), 1);
emit foo.sigGoToStateOne();
state1.wait();
QCOMPARE(state1.count(), 2);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
FooTest test;
QTest::qExec(&test, a.arguments());
QMetaObject::invokeMethod(&a, "quit", Qt::QueuedConnection);
return a.exec();
}
#include "main.moc"
I am forcing all signal invocations to be done from the event loop, so that the event transitions will only happen while the event loop is running. This makes the test code uniformly wait after each transition. Otherwise, the second wait would time out:
Q_SLOT void test1() {
SignalSpy state1(&m_foo.m_state1, SIGNAL(entered()));
SignalSpy state2(&m_foo.m_state2, SIGNAL(entered()));
m_foo.start();
state1.wait();
QCOMPARE(state1.count(), 1);
emit m_foo.sigGoToStateTwo(); // The state2.entered() signal is emitted here.
state2.wait(); // But we wait for it here, and this wait will time out.
QCOMPARE(state2.count(), 1); // But of course the count will match.
emit m_foo.sigGoToStateOne();
state1.wait(); // This would timeout as well.
QCOMPARE(state1.count(), 2);
}
This can be worked around without the use of explicit queued calls by the use of a signal spy class that internally uses a queued connection.
Kuba Ober gives a very good analysis of how to use the test framework & SignalSpy to do in depth testing of your state machine.
If all you're trying to do is generate a sigGoToStateX() from a test file then don't forget that you can chain signals together.
So for example given a class "Tester":
class Tester : public QObject {
Q_OBJECT
public:
Tester(Foo *fooClass) {
//Connecting signals gives you the kind of behaviour you were asking about
connect(this, SIGNAL(testTransitionToState1()), fooClass, SIGNAL(sigGoToState1()));
connect(this, SIGNAL(testTransitionToState2()), fooClass, SIGNAL(sigGoToState2()));
connect(this, SIGNAL(testTransitionToState3()), fooClass, SIGNAL(sigGoToState3()));
}
void SwitchState(int newState) {
//Now any time we emit the test signals, the foo class's signals will be emitted too!
if (newState == 1) emit testTransitionToState1();
else if (newState == 2) emit testTransitionToState1();
else if (newState == 3) emit testTransitionToState1();
}
signals:
void testTransitionToState1();
void testTransitionToState2();
void testTransitionToState3();
}
So for example calling SwitchState(1) will invoke the correct signals for switching to state 1. If this simple case is all you need for testing then that's all you really need.
If you need something more complex, go with the full SignalSpy example.

Resources