Emitting signals from class, if transition in QStateMachine was successful - c++

My problem is the following: I need to create class, which contains QStateMachine instance. This class should have slots through which you could "ask" state machine to make transition to another state. And if transition was successful, my class should emit signal about it. How would I implement this? Class should have ability to emit certain signals according to certain slot invoke.
Here is a small example of class:
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0)
{
mStateMachine = new QStateMachine(this);
QState *s1 = new QState(mStateMachine);
QState *s2 = new QState(mStateMachine);
QState *s3 = new QState(mStateMachine);
s1->addTransition(); // Transition to s2
s2->addTransition(); // Transition to s3
s3->addTransition(); // Transition to s1
mStateMachine->setInitialState(s1);
mStateMachine->start();
}
signals:
toS1();
toS2();
toS3();
public slots:
slotToS1()
{
/* post event to state machine about
transition to state s1,
if transition was successful,
then emit toS1() signal. */
};
slotToS2(){ /* Similar to slotToS1 */};
slotToS3(){ /* Similar to slotToS1 */};
private:
QStateMachine *mStateMachine;
}
I would be very grateful for your help!
UPD:
The slots are representing defferent kinds of transitions, so that outer class (that will be using MyClass) could 'ask' for some transition. So, the slot send event or signal to state machine, it looks on event or signal and (if in right state) makes this transition. And I want to notify outer class with certain signal, that asked before slot (transition) was made successfuly.

To transition on a slot call, you need to somehow bind the slot to a QAbstractTransition. There are two ways of doing it:
Use a QEventTransition and send a relevant event to trigger it.
Use a QSignalTransition and use an internal signal to trigger it.
To emit signals on state transitions, you can connect the QAbstractTransition::triggered or QState::entered or QState::exited signals to other signals. Remember, in Qt a connection target can be either a slot or a signal.
Thus, using signal transitions:
class MyClass : public QObject
{
Q_OBJECT
QStateMachine machine;
QState s1, s2;
Q_SIGNAL void s_go_s1_s2();
Q_SIGNAL void s_go_s2_s1();
public:
Q_SIGNAL void transitioned_s1_s2();
Q_SIGNAL void transitioned_s2_s1();
Q_SLOT void go_s2_s1() { emit s_go_s2_s1(); }
Q_SLOT void go_s1_s2() { emit s_go_s1_s2(); }
explicit MyClass(QObject *parent = 0) : QObject(parent),
s1(&machine), s2(&machine) {
auto s1_s2 = s1.addTransition(this, SIGNAL(s_go_s1_s2()), &s2);
auto s2_s1 = s2.addTransition(this, SIGNAL(s_go_s2_s1()), &s1);
machine.setInitialState(&s1);
machine.start();
connect(s1_s2, &QAbstractTransition::triggered, this, &MyClass:: transitioned_s1_s2);
connect(s2_s1, &QAbstractTransition::triggered, this, &MyClass:: transitioned_s2_s1);
}
}
Using event transitions is a bit harder, since the events you're using must be cloneable by the state machine. The core module's state machine only knows how to clone the None and Timer events - see its cloneEvent implementation.
The widgets module adds support for various GUI/Widgets events - see the cloneEvent implementation there. You could, in a pinch, use such GUI events for your own purposes - after all, they are sent to a plain QObject that doesn't interpret them in a special way.
You can provide your own cloneEvent implementation that links with the others.
#include <private/qstatemachine_p.h>
class MyClass : public QObject
{
Q_OBJECT
QStateMachine machine;
QState s1, s2;
QEvent e_s1_s2, e_s2_s1;
QEventTransition s1_s2, s2_s1;
public:
Q_SIGNAL void transitioned_s1_s2();
Q_SIGNAL void transitioned_s2_s1();
Q_SLOT void go_s2_s1() { QCoreApplication::sendEvent(this, &e_s2_s1); }
Q_SLOT void go_s1_s2() { QCoreApplication::sendEvent(this, &e_s1_s2); }
explicit MyClass(QObject *parent = 0) : QObject(parent),
s1(&machine), s2(&machine),
e_s1_s2((QEvent::Type)(QEvent::User + 1)),
e_s2_s1((QEvent::Type)(QEvent::User + 2)),
s1_s2(this, e_s1_s2.type()),
s2_s1(this, e_s2_s1.type()) {
s1_s2.setTargetState(&s2);
s2_s1.setTargetState(&s1);
s1.addTransition(&s1_s2);
s2.addTransition(&s2_s1);
machine.setInitialState(&s1);
machine.start();
connect(&s1_s2, &QAbstractTransition::triggered, this, &MyClass::transitioned_s1_s2);
connect(&s2_s1, &QAbstractTransition::triggered, this, &MyClass::transitioned_s2_s1);
}
}
static const QStateMachinePrivate::Handler * last_handler = 0;
static QEvent * cloneEvent(QEvent * e) {
if (e->type() >= QEvent::User && e->type() < QEvent::User+100) {
return new QEvent(e->type());
return last_handler->cloneEvent(e);
}
const QStateMachinePrivate::Handler our_handler = {
cloneEvent
};
void registerHandler() {
last_handler = QStateMachinePrivate::handler;
QStateMachinePrivate::handler = &our_handler;
}
Q_CONSTRUCTOR_FUNCTION(registerHandler())
void unregisterHandler() {
QStateMachinePrivate::handler = last_handler;
}
Q_DESTRUCTOR_FUNCTION(unregisterHandler())

I have had the same problem in the past and I have found the easiest way was to inherit from QState with your own QState class and implement 2 methods called QState::onEntry(QEvent * event) and QState::onExit(QEvent * event).
This way you are able to emit any signal you like when you exit and when you enter a new state.
Here is and example:
file mystate.h
#include <QState>
class MyState : public QState
{
Q_OBJECT
public:
explicit MyState(qint32 stateId, QState * parent = 0);
protected:
void onEntry(QEvent * event);
void onExit(QEvent * event);
signals:
void exit(qint32 stateId);
void enter(qint32 stateId);
private:
qint32 stateId;
};
And file mystate.cpp
#include "mystate.h"
MyState::MyState(qint32 stateId, QState *parent)
{
this->stateId = stateId;
}
void MyState::onEntry(QEvent *event)
{
emit enter(stateId);
}
void MyState::onExit(QEvent *event)
{
emit (exit(stateId));
}

Related

How to properly abort a network request in Qt?

I have a class that performs a request to the network and parses the data. How do I properly implement the request abort for it?
Imagine that I have such a class:
class MyClass
{
public:
...
void doRequest()
{
m_reply = m_manager.get(...);
QEventLoop waitForResponse;
connect(m_reply, &QNetworkReply::finished, &waitForResponse, &QEventLoop::quit);
waitForResponse.exec();
// Check if request was aborted (otherwise, application will crash)
if (m_reply == nullptr)
return;
// Check for network errors, write result to m_data and delete m_reply;
...
}
void abort()
{
if (m_reply != nullptr)
m_reply->abort();
}
QString data()
{
return m_data;
}
...
private:
QNetworkAccessManager *m_manager;
QPiinter<QNetworkReply> m_reply;
QString m_data;
}
Here is an example of its use by pressing the button:
class MainWindow : public QMainWindow
{
...
private slots:
MainWindow::on_myButton_pressed()
{
m_myClass->abort();
m_myClass->doRequest();
ui->myTextEdit->setText(m_myClass->data());
}
private:
MyClass m_myClass;
}
When you press the button, if the previous request is not completed, then it is canceled. This works. But under the hood in this case a new request writing data into the QTextEdit and exit the function, then old request returning from it's own loop and writes the same m_data to QTextEdit again.
Is it corrent? Maybe there is a more correct way to implement this?
Nested event loops are the root of all evil. It is much simpler to write a function like doRequest without pretending to the user that it is a synchronous function. It seems that you have already traced the convoluted control-flow that happens when you call abort() and you understand how subsequent calls to doRequest() end up being nested calls due to re-entering the event loop. If you restart your request multiple times, your stack would look something like (the stack grows downwards):
1. main function
2. main event loop
3. [...] (Qt functions)
4. MainWindow::on_myButton_pressed()
5. MyClass::doRequest()
6. QEventLoop::exec()
7. [...] (Qt functions)
8. MainWindow::on_myButton_pressed()
9. MyClass::doRequest()
10. QEventLoop::exec()
11. [...] (Qt functions)
12. MainWindow::on_myButton_pressed() and so on...
Each one of the calls to MainWindow::on_myButton_pressed() need to call ui->myTextEdit->setText() when its nested event loop exits.
An alternative would be make your functions fully asynchronous and rely on signals/slots if you need things to be executed when a particular operation finishes. Here is a minimal implementation for what you are trying to achieve:
#include <QtNetwork>
#include <QtWidgets>
/// A class responsible for communication with the web backend
class Backend : public QObject {
Q_OBJECT
public:
explicit Backend(QObject *parent = nullptr)
: QObject(parent), m_reply(nullptr) {}
public slots:
void doRequest() {
// abort and delete ongoing request (if any)
if (m_reply) {
m_reply->abort();
delete m_reply;
m_reply = nullptr;
}
emit textUpdated(QString());
// send request
QUrl url("http://wtfismyip.com/text");
QNetworkRequest request(url);
m_reply = m_manager.get(request);
// when the request is finished,
QObject::connect(m_reply, &QNetworkReply::finished, [this] {
// if the request ended successfully, read the received ip into m_lastData
if (m_reply->error() == QNetworkReply::NoError)
m_lastData = QString::fromUtf8(m_reply->readAll());
// otherwise, emit errorOccured() signal (if the request has not been
// actively canceled)
else if (m_reply->error() != QNetworkReply::OperationCanceledError)
emit errorOccured(m_reply->errorString());
// in all cases, emit updateText and do cleanup
emit textUpdated(m_lastData);
m_reply->deleteLater();
m_reply = nullptr;
});
}
void abort() {
if (m_reply != nullptr)
m_reply->abort();
}
signals:
void textUpdated(const QString &);
void errorOccured(const QString &);
private:
QNetworkAccessManager m_manager;
QNetworkReply *m_reply;
QString m_lastData;
};
/// A minimal widget that contains a QPushButton and a QLabel
class Widget : public QWidget {
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr) : QWidget(parent) {
m_layout.addWidget(&m_pushButton);
m_layout.addWidget(&m_label);
connect(&m_pushButton, &QPushButton::clicked, this, &Widget::buttonClicked);
}
signals:
void buttonClicked();
public slots:
void updateText(const QString &text) { m_label.setText(text); }
void showError(const QString &error) {
QMessageBox::warning(this, tr("Error"), error);
}
private:
QVBoxLayout m_layout{this};
QPushButton m_pushButton{"Retrieve Name"};
QLabel m_label;
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Backend backend;
Widget widget;
// connect components
QObject::connect(&backend, &Backend::textUpdated, &widget,
&Widget::updateText);
QObject::connect(&backend, &Backend::errorOccured, &widget,
&Widget::showError);
QObject::connect(&widget, &Widget::buttonClicked, &backend,
&Backend::doRequest);
widget.show();
return a.exec();
}
#include "main.moc"

Serialport in a separate QThread

I'd like to insert the serial port in a separate QThread, but the application crashes. I wrote the following C++ classes
Worker.h
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0);
signals:
void finished();
void error(QString err);
public slots:
void process();
};
class WorkerInterface : public QObject
{
Q_OBJECT
public:
explicit WorkerInterface(QObject *parent = nullptr);
~WorkerInterface();
serialport *readSerialPort();
signals:
void threadStoppedChanged();
public slots:
void errorString(QString errorMsg);
void stopThread();
private:
QThread m_thread;
serialPort *m_serial;
};
Worker::Worker(QObject *parent)
: QObject(parent)
{
}
void Worker::process()
{
emit finished();
}
Worker.cpp
WorkerInterface::WorkerInterface(QObject *parent)
: QObject(parent)
, m_thread(this)
{
serialPort::serialPortMaster = new serialPort(nullptr);
m_serial = serialPort::serialPortMaster;
serialPort::serialPortMaster->moveToThread(&m_thread);
connect(&m_thread, SIGNAL(started()),serialPort::serialPortMaster, SLOT(Init()));
m_thread.start();
}
WorkerInterface::~WorkerInterface()
{
m_thread.quit();
m_thread.wait(1000);
if (!m_thread.isFinished())
m_thread.terminate();
}
void WorkerInterface::errorString(QString errorMsg)
{
qDebug() << "error" << errorMsg;
}
void WorkerInterface::stopThread()
{
m_thread.quit();
m_thread.wait(1000);
if (!m_thread.isFinished())
m_thread.terminate();
emit threadStoppedChanged();
}
serialPort* WorkerInterface::readSerialPort()
{
return(m_serialPort);
}
In the main.cpp I wrote the following code:
WorkerInterface workerInterface;
engine.rootContext()->setContextProperty("newserial", workerInterface.readSerialPort());
QQmlComponent component(&engine,QUrl(QStringLiteral("qrc:/Pages/Content/Qml/main.qml")));
QObject *qmlObject = component.create();
When the code arrives at the last instruction in main.cpp, the application crashes and in the QT creator console there is the following messages:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0xee18c0), parent's thread is QThread(0xc8d8b0), current thread is QThread(0x7fffffffdc60)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0xee18c0), parent's thread is QThread(0xc8d8b0), current thread is QThread(0x7fffffffdc60)
QQmlEngine: Illegal attempt to connect to serialPort(0xee1710) that is in a different thread than the QML engine QQmlApplicationEngine(0x7fffffffdc30.
Could someone help me to solve the crash?
Many thanks in advance.
Assuming that you have device which responds with text, the best and simplest way to do it is something like this:
class IODevLineReader
{
Q_OBJECT
public:
explicit IODevLineReader(QObject *parent);
public signals:
void lineWasReceived(const QString &line);
public slots:
void onReadyRead() {
QIODevice *dev = qobject_cast<QIODevice *>(sender());
while (dev && dev->canReadLine()) {
auto lineBytes = dev->readLine();
emit lineWasReceived(lineBytes);
}
}
};
Just connect QSerialPort::readyRead() to IODevLineReader::onReadyRead() and connect some slot to IODevLineReader::lineWasReceived() signal and you are done without use of threads.
And if you still insist to use thread, just use same object tree and move it to specified thread.

Can we emit a signal from a public slot

class MyMainWindow:public QMainWindow {
public:
MyWindow* myWindow() { return myWindow ;}
private:
MyWindow* myWindow;
};
class MyWindow:public Qobject {
private slot:
void mySlot();
};
class MyWindow2: class QWidget {
public slot:
void refreshClick();
signals:
signal1();
};
MyWindow2::MyWindow2(QMainWindow* parent) {
QPushButton* refresh;
QObject::connect(refresh,SIGNAL(clicked()), this, SLOT(refreshClicked()));
if(parent) {
QObject::connect(this,SIGNAL(signal1),parent->myWindow(),SLOT(mySlot));
}
}
void MyWindow2::refreshClicked(){
emit signal1();
}
I want to know if it is legal to emit signal1 from slot refreshClicked and also are there any cons of emitting a signal from within a slot
Yes, it is perfectly ok. But if your only goal is to "forward" a signal, you can also connect your "incoming" signal directly to the signal you are emmitting. eg.:
connect(advisor , SIGNAL(hasAdvice()),
this , SIGNAL(executeAdvice())
)
But keep in mind that this does not always benefit the extendablity of your code.

Qt emitted signal is not received

I'm not able to receive my custom signal in the supposed SLOT. Here is my code:
mainwindow.h:
class HistoryItem {
public:
QString channel;
};
class dbThread : public QObject
{
Q_OBJECT
public:
dbThread();
signals:
void historyLoaded(QList<HistoryItem*> innerResult);
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void historyLoaded(const QList<HistoryItem*> innerResult);
mainwindow.cpp:
connect(dbtrad, SIGNAL(historyLoaded(QList<HistoryItem*>*)), this, SLOT(historyLoaded(QList<HistoryItem*>*)));
void MainWindow::historyLoaded(QList<HistoryItem*> innerResult) {
qDebug() << "historyLoaded()...";
}
And this is how I emit the signal:
QList<HistoryItem*> innerResult;
while (queryInner.next()) {
QString channelIDInner = queryInner.value(0).toString();
HistoryItem* item = new HistoryItem();
item->channel = channelIDInner;
innerResult.append(item);
}
qDebug() << "DONE LOADING.....";
emit historyLoaded(innerResult);
However, qDebug() << "historyLoaded()..."; is never executed.
Any ideas what the problem could be?
It seems you're using threads. Using QList when signaling across threads (or using Qt::QueuedConnection in general) requires some extra work. Basically you need to define the QList<T> type using typedef and then register it using qRegisterMetaType:
typedef QList<HistoryItem*> HistoryList_t;
...
qRegisterMetaType<HistoryList_t>("HistoryList_t");
Then use this type in your signals and slots:
public slots:
void historyLoaded(const HistoryList_t &list);
Check return value of your connect, it should fail. There is an extra * in SIGNAL(historyLoaded(QList<HistoryItem*>*)), should be SIGNAL(historyLoaded(QList<HistoryItem*>)). Fix your SLOT() too.

Qt Signals and Slots Confusion

I have been reading about Qt signals and slots and I am trying to get this to work, but until now without success. I hope someone can point me in the right direction.
I have two files, homeCommand.cpp and messagelogcommand.cpp. I have a QPlainTextEdit object in messagelogcommand.cpp that I want to update from homeCommand.cpp.
How can I do this using signals and slots? My signal is being called, as my QDebug is being printed out once a second, however the widget does not update.
This is what I am trying to do:
In MessageLogCommand.h
class MessageLogCommand : public QWidget
{
Q_OBJECT
public:
explicit MessageLogCommand(QWidget *parent = 0);
QLabel *homeLabel;
QPlainTextEdit *messageLog;
public Q_SLOTS:
void updateWidgets(const QString &text);
};
homeCommand.h
class homeCommand : public QWidget
{
Q_OBJECT
Q_SIGNALS:
void textChanged(const QString &text);
public:
explicit homeCommand(QWidget *parent = 0);
public slots:
void run(void);
void getHealthStatusPacket(void);
homeCommand.cpp
homeCommand::homeCommand(QWidget *parent) : QWidget(parent)
{
...
//Timer
QTimer *timer = new QTimer(this);
timer->setSingleShot(false);
connect(timer, SIGNAL(timeout()), this, SLOT(run()));
timer->start(1000);
setLayout(layout);
}
void homeCommand::run(void)
{
getHealthStatusPacket();
}
void homeCommand::getHealthStatusPacket(void)
{
...
Q_EMIT textChanged("ZOMG");
}
In MessageLogCommand.cpp
MessageLogCommand::MessageLogCommand(QWidget *parent) : QWidget(parent)
{
QGridLayout *layout = new QGridLayout;
QWidget::setFixedHeight(600);
//Sub-system Label
homeLabel = new QLabel("GSS Message Log");
QFont subsystemFont = homeLabel->font();
subsystemFont.setPointSize(12);
subsystemFont.setBold(true);
homeLabel->setFont(subsystemFont);
layout->addWidget(homeLabel, 0, 0);
//Event Log
messageLog = new QPlainTextEdit();
messageLog->setFixedHeight(500);
messageLog->setFixedWidth(600);
layout->addWidget(messageLog, 2,0);
setLayout(layout);
}
void MessageLogCommand::updateWidgets(const QString &text)
{
qDebug() << "Here";
messageLog->appendPlainText(text);
}
In main.cpp
MessageLogCommand s;
homeCommand m;
QObject::connect(&m, SIGNAL(textChanged(QString)), &s, SLOT(updateWidgets(QString)));
A very basic example is:
class MainClass:public QObject //class must be derived from QObject!
{
Q_OBJECT //this macro must be in the class definition
//so the moc compiler can generate the necessary glue code
public:
void doSomething() {
...
Q_EMIT textChanged(someText);
}
Q_SIGNALS:
void textChanged(const QString &text);
};
class SubClass:public QObject
{
Q_OBJECT
public Q_SLOTS:
void onTextChanged(const QString &text) { //do not inline
//do something
}
};
int main()
{
QApplication a;
MainClass m;
SubClass s;
QObject::connect(&m, SIGNAL(textChanged(QString)),
&s, SLOT(onTextChanged(QString))); //const and & are removed from
//the arguments
return a.exec(); //run the event loop
}
So, there are 2 things important:
1. Signals and slots must be declared in a class derived from QObject
2. The classes containing signals and slots declarations must add the Q_OBJECT macro to the class declaration
To keep it simple for you: always declare your classes containing signals or slots in a header file (never in a .cpp file).
A very good starting point for signals and slots is: http://woboq.com/blog/how-qt-signals-slots-work.html but also the official Qt doc does it: http://qt-project.org/doc/qt-4.8/signalsandslots.html
Basically what happens: you declare some special methods (signals and slots), at the compilation phase Qt generates extra CPP files which take care of your methods (moc) then everything is compiled and linked together and at the end when Qt or someone else emits a signal it will go to the corresponding slot.
I try to explain it.
In main.h you should to declare a signal:
signals:
void textChanged(const QString& text);
And in messagelog.h you should to declare a slot:
public slots:
void updateWidgets(const QString& text);
In main.cpp you should emit this signal:
void TheMethod() {
emit this->textChanged("Your text/value");
}
In messagelog.cpp you should get this value:
// Note: Normalized signal/slot signatures drop the consts and references.
connect(&a, SIGNAL(textChanged(QString)), this, SLOT(updateWidgets(QString)));
void updateWidgets(const QString& text) {
messageLog = new QPlainTextEdit();
messageLog->setFixedHeight(500);
messageLog->setFixedWidth(600);
messageLog->setPlainText(text)
layout->addWidget(messageLog, 2,0);
}
I think it should works.
UPDATE:
Complete example: https://dl.dropboxusercontent.com/u/29647980/test.zip