Cannot create Qstatemachine inside constructor



  • Ok getting a problem where the state will not change when inside a constructor. When it's in main it works fine, so at a bit of a loss really now. If anyone has an idea what I am doing wrong please let me know.

    main.cpp
    @#include "widget.h"
    #include <QApplication>
    #include <QPushButton>
    #include <QVBoxLayout>
    #include <QStateMachine>
    #include <QState>
    #include <QRectF>
    #include <QLabel>

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);

    Widget w;
    w.show();
    
    return a.exec&#40;&#41;;
    

    }
    @

    widget.cpp
    @#include "widget.h"
    #include "ui_widget.h"

    #include <QApplication>
    #include <QPushButton>
    #include <QVBoxLayout>
    #include <QStateMachine>
    #include <QState>
    #include <QRectF>
    #include <QLabel>

    Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
    {
    ui->setupUi(this);

    QWidget *window = new QWidget(this);
    
    /* Here created the buttons */
    
    QPushButton *button1 = new QPushButton ("1");
    //QLabel *Current_State(&window);
    QLabel *Current_State= new QLabel;
    Current_State->setText("NO STATE");
    // QPushButton *button2 = new QPushButton ("2");
    //QPushButton *button3 = new QPushButton ("3");
    
    /* Here created the Layout */
    
    QVBoxLayout  *vbox = new QVBoxLayout;
    
    /* Here the buttons are added  in the Layout */
    
    vbox->addWidget(button1);
    vbox->addWidget(Current_State);
    
    window->setLayout(vbox);
    window->resize(200,100);
    
    /* The state machine is created */
    
    QStateMachine machine;
    
    /* State are created  */
    
    QState *state1 = new QState();
    QState *state2 = new QState();
    QState *state3 = new QState();
    
    state1->assignProperty(Current_State, "text", "In State 1");
    state2->assignProperty(Current_State, "text", "In State 2");
    state3->assignProperty(Current_State, "text", "In State 3");
    
    
    state1->addTransition(button1, SIGNAL(clicked()), state2);
    state2->addTransition(button1, SIGNAL(clicked()),state3);
    state3->addTransition(button1, SIGNAL(clicked()),state1);
    
    /* States are added in state machine */
    
    machine.addState(state1);
    machine.addState(state2);
    machine.addState(state3);
    
    /*  Set the state initial for the state machine */
    
    machine.setInitialState(state1);
    
    /* Start the state machine */
    machine.start();
    

    }

    Widget::~Widget()
    {
    delete ui;
    }@



  • QStateMachine machine is stack variable.

    Try the following

    QStateMachine *machine = new QStateMachine;


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.