3

Is there any way to check that the ui elements(line edit,combo box,etc.) of the dialog has been changed.

What I want is to show a message to the user if he changes the value of any single ui element, saying that details have been partially filled.

What i can do is use connect for each ui element & based on the value changed of each element i am setting a boolean flag & at the time of close event i am checking that boolean flag.
But Its quite complicate to check it for each widget. Is there any easier way. Code that I am using for single ui element is,

connect(ui->leAge,SIGNAL(textChanged(QString)),this,SLOT(functChanged())); //In Constructor

void DemoDialog::functChanged()   //Will be called if value of line edit (ui->leAge) is changed
{
    flag=true;
}

void DemoDialog::closeEvent(QCloseEvent *event)
{
 if (flag) {
    if (QMessageBox::warning(this,"Close","Do you want to close?",QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes) {
        this->close();
   }
}
krohit
  • 792
  • 1
  • 7
  • 26

2 Answers2

3

You can't reimplement closeEvent to prevent closing a window. The close() call that you do is either redundant or an error (infinite recursion), since a closeEvent method call is just a way of being notified that a closing is imminent. At that point it's too late to do anything about it.

Keep in mind the following:

  1. Closing a dialog usually is equivalent to canceling the dialog. Only clicking OK should accept the changes.

  2. When a user wants to close a dialog, you don't have to ask them about it. They initiated the action. But:

  3. It is proper to ask a user about dialog closure if there are changes have not been accepted - on platforms other than OS X.

So, you have to do several things:

  1. Reimplement the void event(QEvent*) method. This allows you to reject the close event.

  2. Offer Apply/Reset/Cancel buttons.


Your flag approach can be automated. You can find all the controls of the dialog box and set the connections automatically. Repeat the statement below for every type of control - this gets tedious rather quickly:

foreach(QTextEdit* w, findChildren<QTextEdit*>())
  connect(w, SIGNAL(textChanged(QString)), SLOT(functChanged()));

You can leverage the meta property system. Most controls have a user property - that's the property that holds the primary value of the control (like text, selected item, etc). You can scan all of the widget children, and connect the property change notification signal of the user property to your flag:

QMetaMethod slot = metaObject().method(
                     metaObject().indexOfSlot("functChanged()"));
foreach (QWidget* w, findChildren<QWidget*>()) {
  QMetaObject mo = w->metaObject();
  if (!mo.userProperty().isValid() || !mo.userProperty().hasNotifySignal())
    continue;
  connect(w, mo.notifySignal(), this, slot);
}

Each widget is a QObject. QObjects can have properties, and one of the properties can be declared to be the user property. Most editable widget controls have such a property, and it denotes the user input (text, numerical value, selected index of the item, etc.). Usually such properties also have change notification signals. So all you do is get the QMetaMethod denoting the notification signal, and connect it to your function that sets the flag.


To determine the changed fields, you don't necessarily need a flag. In many dialog boxes, it makes sense to have a data structure that represent the data in the dialog. You can then have a get and set method that retrieves the data from the dialog, or sets it on the dialog. To check for changed data, simply compare the original data to current data:

struct UserData {
  QString name;
  int age;
  UserData(const QString & name_, int age_) :
    name(name_), age(age_) {}
  UserData() {}
};

class DialogBase : public QDialog {
  QDialogButtonBox m_box;
protected:
  QDialogButtonBox & buttonBox() { return m_box; }
  virtual void isAccepted() {}
  virtual void isApplied() {}
  virtual void isReset() {}
  virtual void isRejected() {}
public:
  DialogBase(QWidget * parent = 0) : QDialog(parent) {
    m_box.addButton(QDialogButtonBox::Apply);
    m_box.addButton(QDialogButtonBox::Reset);
    m_box.addButton(QDialogButtonBox::Cancel);
    m_box.addButton(QDialogButtonBox::Ok);
    connect(&m_box, SIGNAL(accepted()), SLOT(accept()));
    connect(&m_box, SIGNAL(rejected()), SLOT(reject()));
    connect(this, &QDialog::accepted, []{ isAccepted(); });
    connect(this, &QDialog::rejected, []{ isRejected(); });
    connect(&buttonBox(), &QDialogButtonBox::clicked, [this](QAbstractButton* btn){
      if (m_box.buttonRole(btn) == QDialogButtonBox::ApplyRole)
        isApplied();
      else if (m_box.buttonRole(btn) == QDialogButtonBox::ResetRole)
        isReset();
    });
  }
}

class UserDialog : public DialogBase {
  QFormLayout m_layout;
  QLineEdit m_name;
  QSpinBox m_age;
  UserData m_initialData;
public:
  UserDialog(QWidget * parent = 0) : QDialog(parent), m_layout(this) {
    m_layout.addRow("Name", &m_name);
    m_layout.addRow("Age", &m_age);
    m_age.setRange(0, 200);
    m_layout.addRow(&buttonBox());    
  }
  /// Used by external objects to be notified that the settings
  /// have changed and should be immediately put in effect.
  /// This signal is emitted when the data was changed.
  Q_SIGNAL void applied(UserData const &);
  UserData get() const {
    return UserData(
      m_name.text(), m_age.value());
  }
  void set(const UserData & data) {
    m_name.setText(data.name);
    m_age.setValue(data.age);
  } 
  void setInitial(const UserData & data) { m_initialData = data; }
  bool isModified() const { return get() == m_initialData; }
protected:
  void isAccepted() Q_DECL_OVERRIDE { emit applied(get()); }
  void isApplied() Q_DECL_OVERRIDE { emit applied(get()); }
  void isReset() Q_DECL_OVERRIDE { set(m_initialData); }
};
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • Thanks for your reply It had really helped, now i am using foreach loop for each widget (i.e. QLineEdit,QTextEdit,QComboBox, QDateEdit). But is there any other way of checking for widget directly(foreach loop for QWidget) which are modifiable (i.e. because that can be easy as single foreach loop is used). – krohit Apr 04 '14 at 10:49
0

If you're only checking whether the input fields are filled when the Dialog closes, you don't need the flags you can only check if there is any input.

If you are filling the input fields programatically at some points but are also only interested in the change when the dialog closes, you can also check in the close function whether the current input is equal to the one you set earlier.

From the code you posted, I can't really see what you need the flags for.

Bowdzone
  • 3,827
  • 11
  • 39
  • 52
  • In case suppose there are 20 to 30 ui elements in my dialog then by checking each input, it will be a huge no. of comparisons which is surely not reliable. – krohit Apr 03 '14 at 14:20
  • Well is having a flag for each one of it better? – Bowdzone Apr 03 '14 at 14:41