c++qtvalidationqspinbox

Validation in QSpinBox


I have QSpinBox which should take only odd numbers, so I've set initial value to 3 and step to 2.

QSpinBox* spinBox = new QSpinBox;
spinBox->setValue(3);
spinBox->setSingleStep(2);

When I'm using spin box arrows to modify value everything is ok. But when I input value from keyboard it can take not odd numbers to.

So is it possible to set validation which fulfills my requirements without inheriting QSpinBox and redefining its validate method?

My current solution is checking in slot if the value is odd:

void MyWidget::slotSetSpinBoxValue(int value)
{
    if(value%2 != 0)
    {
         //call function which takes only odd values
    }
    else
    {
        //here I want to show some kind off message that value can only be odd
        //call function with --value parameter
    }
}

Second question is how to show some tip for QSpinBox? I would like to show tip like tool tip is shown with message that QSpinBox value should be odd. I've found statusTip property in QWidget but cant find example how to use it.


Solution

  • Well you can make a workaround using the valueChanged() slot:

    void MainWindow::on_spinBox_valueChanged(int arg1)
    {
        if( arg1 % 2 == 0)
        {
            //for even values, show a message 
            QMessageBox b;
            b.setText("Only odd values allowed!");
            b.exec();
            //and then decrease the value to make it odd 
            ui.spinBox->setValue( arg1 - 1 );
        }
    }
    

    Now if you want to keep the old value in case the used enters an even number, you will have to either inherit from QSpinBox, or use an event filter to catch key press events, and act before the value gets changed.

    To show the message when the user hovers his/her mouse over the spinbox, you will need to set the box's toolTip, which holds the string that will be shown:

    spinbox with tooltip

    UPDATE: If you don't want a message box, you can: