Search code examples
qtqpushbuttonqlineeditqdialog

QLineEdit emits returnPressed when getting focus triggered by other returnPressed singal


I've 2 QlineEdit and a QPushbutton

QLineEdit *field1 = new QlineEdit();
QLineEdit *field2 = new QLineEdit();
QPushButton *button = new QPushButton();

What I want:

  • If the user presses return in field1 the focus shall be changed to field2.
  • If the user presses return in field2 the button shall be clicked.

For this I have:

/* A */ connect(field1, &QLineEdit::returnPressed, field2, QOverload<>::of(&QLineEdit::setFocus));
/* B */ connect(field2, &QLineEdit::returnPressed, button, &QPushButton::click);
/* C */ connect(submit, &QPushButton::clicked, this, &SomeClass::SomeFunction);

What happens now is:

  1. If I press return in field1, focus goes to field2, but button emits clicked().
  2. If I press return in field2, button emits two times clicked().

For point 1 I can assume that the return key pressed event is still active after setting the focus to field2. Is there a way to avoid this? But if this is the case why the button only emits once the clicked() and not twice like in the next step?

Point 2 can be solved if i replace connect B with

/* B */ connect(field2, &QLineEdit::returnPressed, button, &QPushButton::toggle);

Then clicked() is emitted only once. But this is not clear to me. toggle() should only work for checkable buttons, but the button is not checkable. And also clicked() should not be emitted if toggle() is called.

Do I misunderstand these concepts?

I'm using Qt 5.12.9

Update

During writing I tested a bit around and changed the parent object form QDialog to QWidget which solves my problems. So I assume that hitting return on a QDialog somehow clicks the button. Maybe anyone can explain it to me. Thanks in advance.


Solution

  • QDialog has a default button that is triggered on Return pressed.
    That why you always have an extra clicked() in both cases.

    QDialog default button