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

Make qml rectangle the same color as background



  • I have a rectangle defined in Qt quick as :

    Rectangle{
         id: toolbar
         width: 420
         height: 100
         color: "#303030"
    }
    

    I want to dynamically define the color to match the background color I defined in qtquickcontrols2.conf:

    [Controls]
    Style=Material
    
    [Material]
    Theme=Dark
    ;Accent=BlueGrey
    ;Primary=BlueGray
    ;Foreground=Brown
    Background=#404040
    

    How can I make the background color of the rectangle match the theme color without manually changing it?



  • Simple solution:

    Rectangle{
         id: toolbar
         width: 420
         height: 100
         color: background.color
    }
    

    unfortunately this solution means the rectangle will appear white in design previews, which can make designing dark-mode UI difficult



  • As you override the default settings for the material style with the conf file, you can simply address them:

    //import QtQuick.Controls.Material 2.12
    
    Rectangle{
        id: toolbar
        width: 420
        height: 100
        // Material.accent | Material.primary | Material.foreground | Material.background
        color: Material.background
        Component.onCompleted: console.debug(color)
    }
    

Log in to reply