Important: Please read the Qt Code of Conduct -

[SOLVED]QVariant will drop alpha value when save QColor?

  • It seems that QVariant only save QColor as #RRGGBB, and all other info will no longer exists, including alpha value of QColor.

    So, any better way to work around this?

  • Lifetime Qt Champion

    If you save the color in a text file, you could test for the QColor type and make the string yourself
    Assuming you are using a QTextStream;


    if (variant.type() == QVariant::Color) {
    QColor color = variant.value<QColor>();
    QString colorText = QString("#%1%2%3%4").arg(
    stream << colorText;

    And then parse the string in using a similar logic when you read the file

  • Thanks~

  • If you only want to save RGBA values in a QVariant, you can save and restore like this with less overhead :
    QColor color;
    QVariant v(color.rgba());

    QColor color = QColor::fromRgba(v.toUInt());

    note though that the QColor is stored as a 32bit unsigned integer.

  • Indeed, saving as integer is more efficient. I've changed my code to this^^

Log in to reply