[英]Change property of the QML singleton with C++
I'm implementing a simplified Ubuntu Touch-like palette (not per-element one). 我正在实现一个简化的Ubuntu Touch-like调色板(不是每个元素一个)。
There is a GlobalPaletteSetting
singleton: 有一个GlobalPaletteSetting
单例:
pragma Singleton
import QtQuick 2.5
QtObject {
property Palette current: NonePalette {}
}
and some palette classes like NonePalette
or Dark
: 以及一些调色板类,如NonePalette
或Dark
:
Palette {
normal: PaletteValues {
background: "white"
backgroundText: "black"
base: "white"
baseText: "black"
foreground: "white"
foregroundText: "black"
overlay: "white"
overlayText: "black"
field: "white"
fieldText: "black"
selection: "pink"
}
}
So, the global palette can be changed in QML: 因此,可以在QML中更改全局调色板:
import "Customization/Palettes/Dark"
//...
DarkPalette {
id: dark
}
Component.onCompleted: {
GlobalPaletteSetting.current = dark
}
I want to set the global palette by setting the environment variable. 我想通过设置环境变量来设置全局调色板。 Just like the QtQuick styles are working. 就像QtQuick风格一样。
So, an access to GlobalPaletteSetting
is needed from C++. 因此,需要从C ++访问GlobalPaletteSetting
。 And also a method to load QML files with palettes and setting the GlobalPaletteSetting.current
. 还有一种用调色板加载QML文件并设置GlobalPaletteSetting.current
。
How to do that? 怎么做?
Here's the code I came up with: 这是我提出的代码:
QQmlComponent component(engine());
const char *source =
"import QtQuick 2.0\n"
"import Components 1.0\n"
"QtObject {\n"
" property var style: CustomStyle\n"
" function setColor(c) { CustomStyle.headerColor = c; }\n"
"}";
component.setData(source, QUrl());
QObject *item = component.create();
QObject *style = qvariant_cast<QObject*>(item->property("style"));
style->setProperty("headerColor", QColor(255, 0, 0));
Here, CustomStyle
is my style definition, a singleton. 这里, CustomStyle
是我的样式定义,单身。 You can find a complete example at https://goo.gl/ItJGIf 您可以在https://goo.gl/ItJGIf找到完整的示例
The recommendation to use objectName
did not work for me - whether I put it at the top level of my singleton component, or in a child item, findChild
returns 0. It also does not work on top-level of regular components, only children thereof. 使用objectName
的建议对我来说不起作用 - 无论我将它放在我的单例组件的顶层,还是在子项中, findChild
返回0.它也不适用于常规组件的顶级组件,只有它的子组件。 You can find my attempt at https://goo.gl/Iqj9Ap 您可以在https://goo.gl/Iqj9Ap找到我的尝试
Regarding your second question, about loading your style definition at runtime, you can adjust the above code - use setData
or loadUrl
to load component definition, use create
to create an instance, and then set the instance. 关于第二个问题,关于在运行时加载样式定义,可以调整上面的代码 - 使用setData
或loadUrl
加载组件定义,使用create
创建实例,然后设置实例。 In fact, you can do engine()->rootContext()->setContextProperty("style", ...)
so that everything in your QML can access 'style' variable, which might be easier than having a singleton. 实际上,您可以执行engine()->rootContext()->setContextProperty("style", ...)
以便QML中的所有内容都可以访问“样式”变量,这可能比单个变量更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.