SebastianH
SebastianH

Reputation: 786

QStrings isNull out of QSettings is wrong

I notice that QSettings is not able to store the isNull property of a QString. In other cases (QTime) the QSettings works as expected. Do I something wrong?

#include <QTime>
#include <QString>
#include <QSettings>
#include <iostream>
int main(int argc, char *argv[])
{
    QString str;
    QTime time;
    std::cout << "String is null: " << std::boolalpha << str.isNull() << std::endl;
    std::cout << "Time is null: " << std::boolalpha << time.isNull() << std::endl;
    QSettings settings("Settings");
    settings.setValue("string", str);
    settings.setValue("time", time);
    std::cout << "String is null: " << std::boolalpha << settings.value("string").toString().isNull() << std::endl;
    std::cout << "Time is null: " << std::boolalpha << settings.value("time").toTime().isNull() << std::endl;
    return 0;
}

The output is

String is null: true
Time is null: true
String is null: false
Time is null: true

Upvotes: 1

Views: 438

Answers (2)

ypnos
ypnos

Reputation: 52367

Note from the documentation: "Qt makes a distinction between null strings and empty strings for historical reasons." I would assume it is better not to rely on this distinction. Instead of setting a null string you would be better off to not set the option at all (or explicitely unset it).

The practical reason for QSettings not being able to store null string is most probably that the storage format simply does not support this. One common format to store settings is the INI format (see here) which is unable to provide a distinction between empty and null.

Apart from that, I would use QVariant::isNull() instead of converting to string.

Upvotes: 3

Chusya
Chusya

Reputation: 100

Try type settings.value("string").isNull() instead of settings.value("string").toString().isNull(). Because you try cast to String type null-value.

I've used this (how to initialize a QString to null?) post for answer to you

Upvotes: 0

Related Questions