Solved Using machine states correctly
-
Hello,
I'm trying to implement to states in my program. Those are the relevant code snippets (it isn't the whole code, I've deleted some of the functions as to make it shorter):
//Header file #ifndef JAPANESEMEMORISER_HPP #define JAPANESEMEMORISER_HPP #include <QMainWindow> #include <QStateMachine> #include "configurationbox.hpp" #include "sessionbox.hpp" namespace Ui { class JapaneseMemoriser; } class JapaneseMemoriser : public QMainWindow { Q_OBJECT private: Ui::JapaneseMemoriser *ui; QState *configurationState = nullptr; QState *sessionState = nullptr; void configureStates(); void enterSessionMode(); void enterConfigurationMode(); }; #endif // JAPANESEMEMORISER_HPP
//Source file #include "japanesememoriser.hpp" #include "ui_japanesememoriser.h" #include <QDesktopWidget> #include <QDebug> JapaneseMemoriser::JapaneseMemoriser(QWidget *parent) : QMainWindow(parent), ui(new Ui::JapaneseMemoriser), configBox(new ConfigurationBox(this)), sessionBox(new SessionBox(this)) { ui->setupUi(this); configureStates(); connect(configurationState, &QState::entered, this, &JapaneseMemoriser::enterConfigurationMode); connect(sessionState, &QState::entered, this, &JapaneseMemoriser::enterSessionMode); } void JapaneseMemoriser::configureStates() { QStateMachine qmachine; configurationState = new QState(); sessionState = new QState(); configurationState->addTransition(ui->sessionButton, &QPushButton::pressed, sessionState); sessionState->addTransition(ui->sessionButton, &QPushButton::pressed, configurationState); qmachine.addState(configurationState); qmachine.addState(sessionState); qmachine.setInitialState(configurationState); qmachine.start(); } void JapaneseMemoriser::enterConfigurationMode() { ui->sessionButton->setText("Start Session"); sessionBox->setVisible(false); configBox->setVisible(true); } void JapaneseMemoriser::enterSessionMode() { ui->sessionButton->setText("End Session"); sessionBox->setVisible(true); configBox->setVisible(false); }
I've used this site as a guide line for the configuration. However, for some reason it doesn't seem to work. The program does start, but none of the implemented functionalities seem to work. Once I close the program, I get an "unexpected crash" error message. I have the feeling that it might be because the QStateMachine works asynchronously (although I'm not sure). If so, how should I change the program?
-
Could it be because the qmachine is local and will be destroyed when configureStates() exits ?
-
Ha, yep this was the problem. Thanks a lot!