Styling QML without manually marking each property to be styled

懵懂的女人 提交于 2019-11-29 23:49:43

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...).

It could also be helpful to look at Qt Quick Controls Styles

When using Controls Styles it is not necessary to explicitly assign each property in the target control. All properties can be defined in a separate [ControlName]Style component (e.g. ButtonStyle).
Then in target component (e.g. Button) you can just reference to style component in one line of code.

The only one downside here is that Style components are available for Qt Quick Controls only. Not for any Qt Component.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!