I found a solution by consulting various forum threads.
Start by developing your themes similar to the approach of this user, inheriting from AbstractStyle
for increased flexibility.
The property
will be determined by the output of a JS
function:
import "qrc:/graphics/componentCreation.js" as Theme
Item
{
id: homeViewItem
anchors.centerIn: parent
// Load default theme during launch
property AbstractTheme currentTheme: Theme.createThemeObject(homeViewItem, "qrc:/redTheme/redTheme.qml");
Rectangle
{
color: currentTheme.textColorStandard;
}
}
componentCreation.js
// Generate theme components and integrate them into the QML files of the apps
var component;
var sprite;
function createThemeObject(item, themePath)
{
component = Qt.createComponent(themePath);
sprite = component.createObject(item);
if (sprite === null)
console.log("componentCreation.js: error creating " + themePath + " object");
else
return sprite;
}
To switch themes when a user clicks a Button
:
Button
{
id: themeButton
text: "Change to blue theme"
onClicked:
{
// Clear redTheme.rcc content, add blueTheme.rcc content
cpp_class.changeTheme("redTheme", "blueTheme")
// Blue theme's content is now accessible, insert it into a QML object
currentTheme = Theme.createThemeObject(homeViewItem, "qrc:/blueTheme/blueTheme.qml")
}
}
Keep in mind that redTheme.qml and blueTheme.qml are stored in qrc
files compiled into rcc
files.
This is the implementation of
changeTheme(const QString&, const QString&)
, which deactivates the old theme and enables the new one:
void cpp_class::changeTheme(const QString &oldTheme, const QString &newTheme)
{
bool un = QResource::unregisterResource(QCoreApplication::applicationDirPath() + "/data/themes/" + app + "/" + oldTheme + ".rcc");
if (!un)
std::cerr << oldTheme.toStdString() << "could not be unregistered" << std::endl;
bool in = QResource::registerResource(QCoreApplication::applicationDirPath() + "/data/themes/" + app + "/" + newTheme + ".rcc");
if (!in)
std::cerr << newTheme.toStdString() << "could not be registered as an external binary resource" << std::endl;
}
Additional helpful resources include:
(starting at slide 34)