Home > Net >  In Pyside6 (Or C Qt), how do I set a custom QML style at runtime?
In Pyside6 (Or C Qt), how do I set a custom QML style at runtime?

Time:12-21

I want to use a custom style for my QML application. I have followed these instructions: https://doc.qt.io/qt-6/qtquickcontrols2-customize.html#creating-a-custom-style

I have a directory structure like this

MyApp/
├─ main.py
├─ QML/
│  ├─ Main.qml
├─ MyStyle/
│  ├─ qmldir
│  ├─ ToolTip.qml

I have created a style by creating a module (using a qmldir, and putting QML files inside it)

My qmldir contains

module MyStyle
ToolTip 3.0 ToolTip.qml

And ToolTip.qml contains

import QtQuick.Templates 2.0 as T
import QtQuick
import QtQuick.Controls

T.ToolTip {
    id: control
    text: qsTr("A descriptive tool tip of what the button does")

    contentItem: Text {
        text: control.text
        font: control.font
        color: "red"
    }

    background: Rectangle {
        border.color: "grey"
    }
}

I then tried to apply this in main.py (The API is very similar to the C one)

app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
QQuickStyle.setStyle("MyStyle")
engine.load(QUrl.fromLocalFile(f"{os.path.dirname(__file__)}/QML/Main.qml"))
app.exec()

But during engine.load I get the error:

file:///D:/MyApp/QML/Main.qml: module "MyStyle" is not installed `QQuickStyle.setStyle`

It is interesting that the error only happens once engine.load is reached. QQuickStyle.setStyle does not give an error (however, it also does not error even if nonsense is given).

I have tried adding:

engine.registerModule("MyStyle", os.path.dirname(__file__)   "/MyStyle")

And:

engine.setImportPathList([os.path.dirname(__file__)   "/MyStyle"])

But these also does not work.

How do I install my custom style so I can use it, just like I would use:

QQuickStyle.setStyle("Material")

Thanks

edit

If I add:

engine.addPluginPath(f"{os.path.dirname(__file__)}/MyStyle")
qmlRegisterModule("MyStyle", 1, 0)

Then I do not get the error, but my ToolTip style is still not applied.

CodePudding user response:

Your directory is called Style could you test if it works when you rename it to match your style name MyStyle.

From the documentation you've shared:

The style name must match the casing of the style directory; passing mystyle or MYSTYLE is not supported.

CodePudding user response:

After lots of trial and error, I have found the answer:

app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
#THIS NEEDS TO BE THE PATH WITH THE MODULE DIR, NOT THE MODULE DIR ITSELF
engine.addImportPath(f"{os.path.dirname(__file__)}")    
#NOW YOU CAN ADD IT AS A STYLE
QQuickStyle.setStyle("MyStyle")
QQuickStyle.setFallbackStyle("Material")
url = QUrl.fromLocalFile(args.qml)
engine.load(url)
ret = app.exec()
  • Related