Buffer form modifications before commiting them to the model



  • Hello,

    I want to edit some object in a form that have an ok and a cancel button. I have a QObject with property exposed to the QML (name, surname, ...) and this QObject has a reference to a Person object.
    What I have at first is something like that :

    Q_PROPERTY (QString name READ getName WRITE setName NOTIFY nameChanged)
    
    QString PersonViewModel::getName    ()      const
    {
        return person->getName();
    }
    
    void PersonViewModel::setName      (QString     i_value)
    {
        person->set_name(i_value);
        emit nameChanged(i_value);
    }
    

    The issue is that I want to be able to rollback all the modifications made on the form if I click on the cancel button and I want to call the person->setName() only after the user clicks on the ok button.
    I thought of overriding the setProperty method to store all the modification in a map and return the value stored in the map like that

    QString PersonViewModel::getName    ()      const
    {
    if(map.contains("name")
    {
    return map.value("name");
    }
    else
    {
        return person->getName();
    }
    }
    
    void PersonViewModel::setName      (QString     i_value)
    {
    map.insert("name", i_value);
    }
    
    void PersonViewModel::commitChanges()
    {
    if(map.contains("name")
    {
        person->set_name(map.value("name");
        emit nameChanged(i_value);
    }
    map.clear();
    }
    

    Is it ok or is there a more desirable way of doing it with QT ?

    Thanks.



  • The usual way to do this is to put the editor in a QDialog, call QDialog::exec() and check if it returns QDialog::Accepted (i.e. ok was clicked)
    if you need modeless processing you can create the dialog (without binding the properties) and then call setName in a slot connected to the accepted() signal.

    If you show your "form" code and how you call it we can be more specific


Log in to reply
 

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