Question

I'm writing a mini application by means of Qt 4.7. And I have a reoccurring problem with some QSpinBoxes and QDoubleSpinBoxes. I set the editingFinished() signal and when I change the value in any of these fields they send two signals: when the spinbox loses focus and when enter is pressed. So when I press the tab or enter button my program makes the calculations twice. Is there any smart and easy way to set only lostFocus signal?

P.S. I'm newbie in Qt. Sorry for my english, I still learning.

edit:

Thanks a lot for your help netrom!

But it is still something wrong...Should it looks like below? I can compile it and run, but it seems SpinBox still react on Enter button.

dialog.h:

#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QSpinBox>
#include <QKeyEvent>

namespace Ui {
    class SpinBox;
    class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

private:
    Ui::Dialog *ui;

private slots:
    void on_spinBox_editingFinished();
};

class SpinBox : public QSpinBox
{
  Q_OBJECT

public:
  explicit SpinBox(QWidget *parent = 0) : QSpinBox(parent) { }

protected:
  void keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
    case Qt::Key_Return:
    case Qt::Key_Enter:
      return;

    default: break;
    }

    QSpinBox::keyPressEvent(event);
  }
};
#endif // DIALOG_H
Was it helpful?

Solution

You could try checking if the spinbox widget has the focus at the beginning of your slot, it should tell you if the editingFinished() signal was the result of Enter/Return key or the loss of focus.

void Dialog::on_spinBox_editingFinished() {
    if(ui->spinBox->hasFocus()) 
        return;   

    // rest of your code
}

OTHER TIPS

You could override keyPressEvent(QKeyEvent*) and ignore the event when enter is pressed. Another way to do it would be to override focusOutEvent(QFocusEvent*) but make sure that setFocusPolicy() is set to something else than Qt::NoFocus.

Here's an example of the first method: You inherit from QSpinBox and override the keyPressEvent() method and make it ignore the enter/return key:

class SpinBox : public QSpinBox {
  Q_OBJECT

public:
  SpinBox(QWidget *parent = NULL) : QSpinBox(parent) { }

protected:
  void keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
    case Qt::Key_Return:
    case Qt::Key_Enter:
      return;

    default: break;
    }

    QSpinBox::keyPressEvent(event);    
  }
};

Now just use the editingFinished() signal which will only be given when the focus is lost (by using the mouse or tab key, for instance).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top