1

This is my QSpinBox slot method:

void MainWindow::on_sbObjectSize_valueChanged(int arg1)
{
     /*do something*/;
}

I need to distinguish when this value was changed by user (by typing value or click on arrows) and when it was changed from the code (eg. using ui->sbObjectSize->setValue(1)).
Is it possible to do this by overloading something, making own slot/signal or any other way?

rainbow
  • 1,161
  • 3
  • 14
  • 29

1 Answers1

1

Yes, you can do it by checking the value returned from sender(). Let's say you have a button in your UI in your main window and clicking on the button changes the spin box value, then sender()'s value will be the address of the button pointer. qDebug() is really nice, since it will output other information available in your QObject through the metadata available. For instance you can give your QObject a name, and then qDebug() will output that name.

Here's a code snippet:

ui->pushButton->setObjectName("Button1");
connect(ui->pushButton, &QPushButton::clicked, [this] {
    ui->sbObjectSize->setValue(ui->sbObjectSize->value()+1);
});

connect(ui->sbObjectSize, QOverload<int>::of(&QSpinBox::valueChanged), [=] (int value) {
    //based on what this prints, you can write your code so that you can check
    qDebug()  << sender();
    if (sender() == nullptr) {
        qDebug() << "Value changed by via the spin box itself";
    } else {
        qDebug() << "Value changed by: " << sender();
    }
});
santahopar
  • 2,933
  • 2
  • 29
  • 50
  • Can you clarify how in this lambda get `int` argument of `valueChanged`? – rainbow Nov 25 '20 at 00:01
  • 1
    You can read more about it here: https://wiki.qt.io/New_Signal_Slot_Syntax – santahopar Nov 25 '20 at 00:30
  • This topic shows the answer what to when I want to call action that will trigger signal but I don't want to trigger it: https://stackoverflow.com/questions/26358945/qt-find-out-if-qspinbox-was-changed-by-user – rainbow Dec 09 '20 at 16:54
  • @rainbow, cool. If you're gonna go this way, consider using QSignalBlocker instead, it's the RAII version of `blockSignals(true)` followed by `blockSignals(false)`. https://doc.qt.io/qt-5/qsignalblocker.html – santahopar Dec 09 '20 at 18:18