How to create a custom grouping of properties and apply them to different controls?

ぃ、小莉子 提交于 2019-12-25 06:56:37

问题


I have a window with Buttons, TextFields, Labels etc. These all share common properties like font family, color, size etc. What I would like to be able to do is to define a grouping of these properties (called, say, textStyles.MainTitle or textStyles.DescriptiveText etc.) that would include a font family, size and weight, height and color. And then in the QML file I would write something like:

myCustomProperty: textStyles.MainTitle

and this would apply those values to the control. How can I do this?


回答1:


QML controls are styled by implementing their respective styles, for example for Button you have to implement a ButtonStyle.

As for the actual "grouping" you can just use a QtObject

property QtObject textStyles : QtObject {
    property FontLoader mainTitle : FontLoader {...}
    ....
}

You can also extend styled components as dedicated types:

// StyledText.qml

Text {
  font.family: someFont
  font.pixelSize: fontSize
  color: someColor
  font.italic: true
  font.letterSpacing: -1
  ...
}

And then use that by just StyledText {} instead of repeatedly styling regular Text elements.

Where / in what file do I place the QtObject snippet? I don't understand what // StyledText.qml is, or what a FontLoader is.

If you want it to be available in your entire application, you can put it as a property of your root object in main.qml, thanks to dynamic scoping textStyles will resolve from every other file in your project. You can put entire component styles in it as well and share in the project.

StyledText.qml is just an extra qml file you add to your project, you can being with just implementing its body in an existing qml file, then rightclick on Text and select refactoring -> move component into separate file.

A FontLoader is just a regular QML component, you can use it to load specific fonts and use as a font source for text. You don't have to use that, you can use font families from your system fonts as well. The font loader is useful for fonts you bundle with your application.



来源:https://stackoverflow.com/questions/36806326/how-to-create-a-custom-grouping-of-properties-and-apply-them-to-different-contro

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