[Qt-interest] Customizing QSpinBox in Qt4

Lars Amsel lars.amsel at signalion.com
Mon Jun 29 08:23:55 CEST 2009


Hi,

I want to customize the behaviour of QSpinBox. When the user enters a
number directly, numbers outside the range of QSpinBox should be
allowed. They should be truncated to min/max value, when the edit submits.

I managed to do this with this class:

class TolerantSpinBox : public QSpinBox {
public:
   TolerantSpinBox(QWidget* parent = NULL);
protected:
   virtual QValidator::State validate(QString& input, int& pos) const;
   virtual void fixup(QString& input) const;
;

TolerantSpinBox::TolerantSpinBox(QWidget* parent) : QSpinBox(parent) {
}

QValidator::State TolerantSpinBox::validate(QString& input, int& pos)
const {
   QValidator::State result = QSpinBox::validate(input, pos);
   if (result == QValidator::Invalid) {
     bool ok = false;
     input.toInt(&ok, 10);
     if (ok) {
       result = QValidator::Intermediate;
     }
   }
   return result;
}

void TolerantSpinBox::fixup(QString& input) const {
   bool ok;
   int value = input.toInt(&ok, 10);
   if (ok) {
     value = qMin(qMax(value, minimum()), maximum());
     input = QString::number(value);
   } else {
     QSpinBox::fixup(input);
   }
}

This works. What I dislike is, that I have to subclass the spin box to
change something I consider to be a property. In previous versions of Qt
(3.x AFAIK) there was a setValidator-method, which offered the same
functionality. This method seems to be gone with Qt4. Is there a way to
get the desired behaviour without subclassing QSpinBox?

thanks

Lars



More information about the Qt-interest-old mailing list