Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML engine not implicitly converting a bool-string QVarient to bool property

Tags:

c++

qt

qt-quick

qml

I have created a Settings class wrapper around QSettings that provides the following methods for access in QML:

Q_INVOKABLE void setValue(Key key, const QVariant &newValue);
Q_INVOKABLE QVariant value(Key key);

In the user interface, there are CheckBox instances that look like this:

CheckBox {
    checked: Settings.value(Settings.KeySomeBoolSettings)
}

QSettings loads boolean values into QVariant as a QString type as "true" or "false" (which is fine). The problem is when QML converts this implicitly to a boolean expression as needed by the checked property, it is always converting to true (even if it is actually "false"). I've found a workaround to detect whenever a QVariant in Settings::value() is actually a boolean.

QVariant Settings::value(Key key)
{
    QVariant value = mSettings->value(stringNameForKey(key), mDefaultValues[key]);

    //this block is the workaround
    if (QString(value.typeName()) == "QString" &&
        (value.toString() == "false" || value.toString() == "true"))
        return QVariant(value.toBool());

    return value;
}

When detected, the actual QVariant returned is QVariant(value.toBool()) which causes the internal type to actually be bool. So when the internal type is bool, then QML can make the implicit conversion fine. From what I can tell, QML is taking the varient literally as a string, and then converting that to a bool which is always true unless the string is blank. Is this a bug, or am I doing something wrong?

like image 584
Dan Watkins Avatar asked Mar 12 '26 23:03

Dan Watkins


1 Answers

As described in ECMAScript language specification, converting to boolean return false, if value is +0, -0, null, false, NaN, undefined, or the empty string. All other values, including any object or the string "false", converted to true.

Also, in QML you can use Qt Labs Settings QML Type instead of wrapper around QSettings

like image 134
Meefte Avatar answered Mar 14 '26 11:03

Meefte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!