简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM