Solved Out of range condition on Q_PROPERTY
-
I am new to QT and was wondering how are you supposed to handle errors in the QT property system, more specifically on set the functions?
class SomeClass : public QObject
{
Q_OBJECT
Q_PROPERTY(qint16 temperature READ temperature WRITE setTemperature)private:
qint16 mTemperature;
...
...
...void SomeClass::temperature()
{
return mTemperature;
}void SomeClass::setTemperature(qint16 _temperature)
{
if (_temperature < 10 || _temperature > 100)
{
// argument is out of range, what do you do here?
return;
}
mTemperature = _temperature;
}Are you supposed to throw an exception, invoke a signal or what?
Any help would be greatly appreciated. -
HI and welcome to devnet,
Are you supposed to throw an exception, invoke a signal or what?
For sure Qt does not use exceptions.
What usually I do (is not an official Qt guideline) is to force the value to be in the range; you have 2 options depending of what do you need:
- Don't change the value if the proposed value is out-of range;
void MyObject::setValue (int newValue) { if (newValue < MIN_VALUE || newValue > MAX_VALUE) return; if (_v != newValue) { _v = newValue; Q_EMIT valueChanged(_v); } }
- Force the value to the limit values.
void MyObject::setValue (int newValue) { if (newValue < MIN_VALUE) newValue = MIN_VALUE; if (newValue > MAX_VALUE) newValue = MAX_VALUE; if (_v != newValue) { _v = newValue; Q_EMIT valueChanged(_v); } }
Anyway if you have a range (or only one of lower/upper limit) I suggest to define READ ONLY properties for the limits
-
Mcosta,
Thanks for the input, I'll probably use coercion as you suggest seems like the logical thing to do.