Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to get current theme color ?



  • Hello,

    Is there a way to make my QML code be responsive to the colors of the current theme ?

    import QtQuick 2.0
    import QtQuick.Controls 2.0
    import QtQuick.Controls.Material 2.12
    
    Button {
      checkable: true
      autoExclusive: true
    
      Rectangle {
        width: 12
        height: width
        x: 0
        y: 5
        color: Material.accent
        border.color: "black"
        border.width: 1
        radius: width*0.5
      }
    }
    

    Here in my code, I used explicitly Material.accent to set the color of the rectangle, but if I change the theme, that value will be invalid. Is there a global property to get the current accent color, in example theme.accent or qtquicktheme.accent to make my code independant from the Material theme ? I can't find such information in the Qt documentation.

    Regards.



  • Hi,

    You might use SystemPalette:

    SystemPalette {
        id: activePalette
        colorGroup: SystemPalette.Active
      }
    

    then use it somewhere:
    color: activePalette.highlight
    or any of its property that suits your need.

    But You won't find Windows accent color this way. To do so, some registry key has to be read:

    Here is example how to change highlight color with Windows accent color and use it in application palette. (usually done in main.cpp before loading QML).

      QSettings accent(QStringLiteral("HKEY_USERS\\.DEFAULT\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Accent"),
                         QSettings::NativeFormat);
        if (accent.contains(QLatin1String("StartColorMenu"))) {
          int color = accent.value(QLatin1String("StartColorMenu")).toInt();
          int r = color & 0xff;
          int g = (color >> 8) & 0xff;
          int b = (color >> 16) & 0xff;
          auto pal = qApp->palette();
          QColor c(r, g, b);
          pal.setColor(QPalette::Active, QPalette::Highlight, c.lighter(150)); 
        // Accent color is quite strong , so here it is made lighter
          qApp->setPalette(pal);
        }
    

    But how to get some system color under Android (if there is any) I even don't know.



  • @SeeLook Hello, thank you for your answer. I will keep in mind SystemPalette for other use. Unfortunately, I work on Linux. Perhaps is there no solution and I must stick with Material.accent.

    Regards.



  • Under Linux SystemPalete works out of the box.


Log in to reply