pureooze
pureooze

Reputation: 156

How to get the text from a QLineEdit widget and use it in a State Machine?

I am trying to create a program that waits for the user to input something into a line edit widget, and when they hit enter, I want to compare the value to some predefined one (for example "1"). The problem I seem to be having is that I cannot find a way to make this work with the QStateMachine. At the moment, it will wait for the user to press enter and it just switches over to the next state, but I want it to only go to the next state if the input is "1". Here is the code I am using and thank you for any help that you can offer.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->lineEdit, SIGNAL(editingFinished()), this, SLOT(someSlot()));
    setupStateMachine();
}

...

void MainWindow::setupStateMachine()
{
    QStateMachine *machine = new QStateMachine(this);
    QState *s1 = new QState();
    QState *s2 = new QState();
    QState *s3 = new QState();

    s1->assignProperty(ui->label, "text", readFile("intro.txt"));
    s2->assignProperty(ui->label, "text", "In state s2");
    s3->assignProperty(ui->label, "text", "In state s3");

    s1->addTransition(this, SIGNAL(editing()), s2);
    s2->addTransition(this->ui->pushButton, SIGNAL(clicked()), s3);
    s3->addTransition(this->ui->pushButton, SIGNAL(clicked()), s1);

    machine->addState(s1);
    machine->addState(s2);
    machine->addState(s3);
    machine->setInitialState(s1);

    machine->start();

    qDebug() << "State Machine Created";
}

...

void MainWindow::someSlot()
{
    if(ui->lineEdit->text() == "1")
    {
        emit editing();
    }
}

In the header file:

{
...
signals:
    void editing();
...
private slots:
    void someSlot();
...
};

PS: I realize that the signal does not do what I want, but I can't figure out which signal to use.

Upvotes: 1

Views: 2993

Answers (1)

cppguy
cppguy

Reputation: 3713

Perhaps you can connect editingFinished to your own slot. In that slot, check if the input is "1". if so, emit a new signal you pass into addTransition instead of editingFinished

To add a signal to a class, change the class like this (make sure there is a Q_OBJECT declared at the very top of the class):

signals:
    void mySignalName();

Signals are guaranteed protected. You don't write the body of the function. That's what MOC does. So, when you want to call the signal in your class, just call:

emit mySignalName();

emit is just for code documentation. It's #defined to nothing. MOC will generate the body of mySignalName and boil down to calls to the slots you connect it to using QObject::connect.

To add a new slot to your class, add this:

private slots:
    void mySlotName();

Note that you will have to write the body of a slot.

void MainWindow::mySlotName()
{
    if(myLineEdit->text() == "1")
        emit mySignalName();
}

Upvotes: 1

Related Questions