Styling QML without manually marking each property to be styled

前端 未结 2 2016
慢半拍i
慢半拍i 2020-12-24 07:59

I know that QML does not support CSS styling like widgets do, and I have read up on alternative approaches to styling/theming:

  • https://qt-project.org/wiki/QmlS
2条回答
  •  眼角桃花
    2020-12-24 08:16

    The preferred way isn't applying a style on default components, but deriving from these components to create pre-styled custom components.

    What I do for my projects :

    First, I create one centralized 'theme' file, as a JavaScript shared module :

    // MyTheme.js
    .pragma library;
    var bgColor   = "steelblue";
    var fgColor   = "darkred";
    var lineSize  = 2;
    var roundness = 6;
    

    Next, I create custom components that rely on it :

    // MyRoundedRect.qml
    import QtQuick 2.0;
    import "MyTheme.js" as Theme;
    Rectangle {
        color: Theme.bgColor;
        border {
            width: Theme.lineSize;
            color: Theme.fgColor;
        }
        radius: Theme.roundness;
    }
    

    Then, I can use my pre-styled component everywhere with a single line of code :

    MyRoundedRect { }
    

    And this method has a huge advantage : it's really object-oriented, not simple skinning.

    If you want you can even add nested objects in your custom component, like text, image, shadow, etc... or even some UI logic, like color-change on mouse hover.

    PS : yeah one can use QML singleton instead of JS module, but it requires extra qmldir file and is supported only from Qt 5.2, which can be limiting. And obviously, a C++ QObject inside a context property would also work (e.g. if you want to load skin properties from a file on the disk...).

提交回复
热议问题