PDA

View Full Version : QT Animation Simple Pushbutton Help



Pembar
6th May 2009, 13:17
Hey all,

I'm having difficulties incorporating a simple state machine pushbutton in a widget.

The following code works fine:



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

QPushButton *pushButton1 = new QPushButton();
QtStateMachine machine;

QtState *s1 = new QtState(machine.rootState());
s1->assignProperty(pushButton1, "text", "In s1");

QtState *s2 = new QtState(machine.rootState());
s2->assignProperty(pushButton1, "text", "In s2");

QtState *s3 = new QtState(machine.rootState());
s3->assignProperty(pushButton1, "text", "In s3");

s1->addTransition(pushButton1, SIGNAL(clicked()), s2);
s2->addTransition(pushButton1, SIGNAL(clicked()), s3);
s3->addTransition(pushButton1, SIGNAL(clicked()), s1);

pushButton1->resize(200, 200);
pushButton1->show();

machine.setInitialState(s1);
machine.start();

return a.exec();
}


But if I declare a widget in a separate file (widget.cpp and widget.h) and call it from main:


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


Widget w;
w.show();

return a.exec();
}


Definition within the widget:



Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *mainLayout = new QVBoxLayout;
QPushButton *pushButton1 = new QPushButton();

QtStateMachine machine;

QtState *s1 = new QtState(machine.rootState());
s1->assignProperty(pushButton1, "text", "In s1");

QtState *s2 = new QtState(machine.rootState());
s2->assignProperty(pushButton1, "text", "In s2");

QtState *s3 = new QtState(machine.rootState());
s3->assignProperty(pushButton1, "text", "In s3");

s1->addTransition(pushButton1, SIGNAL(clicked()), s2);
s2->addTransition(pushButton1, SIGNAL(clicked()), s3);
s3->addTransition(pushButton1, SIGNAL(clicked()), s1);

machine.setInitialState(s1);
machine.start();

mainLayout->addWidget(pushButton1);
setLayout(mainLayout);
}


The button appears but no text appears. i.e. the state machine doesn't seem to work.

Any help would be deeply appreciate, Thanks.

Regards,
Pembar

Lykurg
6th May 2009, 14:24
Hi, that's a easy c++ issue. *s1 is deleted after the Widget::Widget scope is leaved. Define the states as member variables of the class and it will work.

class Widget
{
//...
private:
QtState *s1;
}
Widget::Widget()
{
//...
s1 = new QtState(machine.rootState());
}

mcosta
6th May 2009, 14:27
The QtStateMachine are destoyed when Widget COnstructor return;

You must dinamically allocate it.


QtStateMachine* machine = new QtStateMachine(this);

Lykurg
6th May 2009, 14:29
The QtStateMachine are destoyed when Widget COnstructor return;
Ah, even better:o

Pembar
6th May 2009, 14:38
God I love you guys.... Thanks much.

Regards,
Pembar