7

Let's suppose I have a QSpinBox, how I can find out if the value was changed manually from user or from a other function?

EDIT: I want to do some actions only when user change values but if your program does it (setValue) I don't want do this actions.

Matthias
  • 461
  • 7
  • 24
  • I have some solution but you need clarify. Do you want do some actions only when user change values but if you do it in your program (setValue for example)you don't want do this actions. – Jablonski Oct 14 '14 at 11:03
  • I saw edit, now I can post my answer, check it please. – Jablonski Oct 14 '14 at 11:08

1 Answers1

14

Possible solution:

ui->spinBox->blockSignals(true);
ui->spinBox->setValue(50);
ui->spinBox->blockSignals(false);

In this case, signal will not be emitted, so all what you can catch by valueChanged() signal is only user's action.

For example:

void MainWindow::on_spinBox_valueChanged(int arg1)
{
    qDebug() << "called";
}

When user change value by mouse or type by keybord, you see "called", but when you setValue with blocking signals, you don't see "called".

Another approach is to provide some bool variable and set it to true before the setValue and check this variable in slot. If it is false(user action) - do some action, if not - don't do(change bool to false). Advantages: you don't block signal. Disadvantages: maybe hard readable code, if slot calls many times, you will many time do this unnecessary checking.

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • 3
    It is such a shame that input related QWidgets in general don't have a convention for user vs programatic value setting... – Troyseph Apr 26 '16 at 08:54
  • 2
    These days `QSignalBlocker` would be the correct way (using RAII), instead of "surrounding" your `setValue` the way you did. – 0xC0000022L Nov 04 '20 at 13:50