T.Zak
T.Zak

Reputation: 309

How to make QLineEdit emit the previous and the current text in a textChanged signal

I want to subclass QLineEdit to emit a new signal which will have the text from the moment it got focus and the new text.

like:

Signals:
  void customTextChanged(const QString& previousText , const QString& currentText);

The purpose of this QLineEdit is to edit the name of an item, in case it exists it disables the Ok_button ( this is done in the on_text_changed(QString) slot).

I want to check if the user changed his mind and did set the previous name or he undoed.

Upvotes: 2

Views: 2703

Answers (1)

T.Zak
T.Zak

Reputation: 309

Thanks to peppe.

The following subclass stores the lineEdit text when focused ,then whenever the text is changed checks if the text is the same as the text at the start and if it is not it emits a textEditedCustom(QString).

goes to header!

class customQLineEdit: public QLineEdit
{
  Q_OBJECT
public :
  explicit customQLineEdit(QWidget* parent = 0 );
  explicit customQLineEdit(const QString &str, QWidget* parent=0);

signals:
  void textEditedCustom(const QString& text);

public slots:
  void on_Text_Edited_custom(const QString& currentText);

protected:
  QString previousText;
  virtual void focusInEvent(QFocusEvent* e);
};

and the .cpp part

customQLineEdit::customQLineEdit(QWidget* parent ):
  QLineEdit(parent)
{
  connect(this , SIGNAL(textEdited(QString)) ,
          this , SLOT(on_Text_Edited_custom(QString)));

}

customQLineEdit::customQLineEdit(const QString &str, QWidget* parent):
  QLineEdit(str , parent)
{
  connect(this , SIGNAL(textEdited(QString)) ,
          this , SLOT(on_Text_Edited_custom(QString)));

}


void customQLineEdit::focusInEvent(QFocusEvent* e)
{
  previousText = text();
  QLineEdit::focusInEvent(e);
}

void customQLineEdit::on_Text_Edited_custom(const QString& txt)
{
  if(previousText !=  txt)
    emit textEditedCustom(txt);
}

Then you subscribe to it like this:

connect( nameLineEdit , SIGNAL(textEditedCustom(QString)) , 
          this , SLOT(on_nameLineEdit _Changed(const QString &)));

Upvotes: 3

Related Questions