Search code examples
c++arraysqtqlineedit

How can I assign lineEdits to some variable?


I am new to working with Qt. And I got stuck at this thing. I have a lot of lineEdits in my application, And the values in it may change any time while the application is running. Values in lineEdits would be only integers. At some stage I need to check the values in lineEdits and compare with an integer array. If they are equal, then the task for user is completed.

Here I want to store all values of lineEdits to an integer array so that I can run a for loop to check if both the arrays are equal instead of making an if condition for each and every lineEdit. Values in array should get updated whenever user changes the value in lineEdit and also value in lineEdit should change when its corresponding value in array changes.

I tried taking a qvector, appending values of lineEdits into it. This vector now has values of lineEdits but does not update values when its corresponding values are changed in vector.

Can anyone please help in how to do this?


Solution

  • You can have a list of pointers to QLineEdits as a class member :

    QList<QLineEdit *> lineEdits;
    

    And add the pointer to linedits to the list when instantiating them :

    QLineEdit * lineEdit = new QLineEdit(this);
    lineEdits->append(lineEdit);
    

    Then QSignalMapper is useful to update array of values when the line edits are updated. QSignalMapper class collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal. So you can have one like:

    QSignalMapper * mapper = new QSignalMapper(this);
    QObject::connect(mapper,SIGNAL(mapped(int)),this,SLOT(OntextChanged(int)));
    

    For each of your line edits you can connect the textChanged() signal to the map() slot of QSignalMapper and add a mapping using setMapping so that when textChanged() is signaled from a line edit, the signal mapped(int) is emitted:

    for(int i=0; i<lineEdits.count(); i++)
    {
        QObject::connect(lineEdits[i], SIGNAL(textChanged()),mapper,SLOT(map()));
        mapper->setMapping(lineEdits[i], i+1);
    }
    

    This way whenever you change a line edit, the mapped(int) signal of the mapper is emitted containing the index of the line edit as a parameter.

    The values of the array could be updated in the OntextChanged slot like :

    void MyClass::OntextChanged(int index)
    {
       values[index-1] = lineEdits[index-1].text().toInt();
    }