Search code examples
c++slotqtwidgetsqspinbox

How to call changeValue of QSpinBox only when user changed value


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?


Solution

  • 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();
        }
    });