Search code examples
qtqmlqtquickcontrols2

Qt Quick Controls 2 hangs when overwriting Button.qml


I'm trying to implement my own style and for this I want to override the built-in objects. Here's what I'm doing:

// main.cpp
QQuickStyle::setStyle("mystyle");

and

// mystyle/Button.qml
import QtQuick 2.5
import QtQuick.Controls 2.1 as Controls

Controls.Button {
    background: Rectangle {
        color: "green"
    }
}

and

// qml.qrc
<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>mystyle/CheckBox.qml</file>
    </qresource>
</RCC>

According to the docs I believe this should work automagically using file selectors.

However, my app hangs on startup. My guess is that I fall into a recursive import. How do I do this correctly?


Solution

  • The Qt Quick Controls 2 styling system is based on QML type registration. When you run your app with mystyle, the type known as QtQuick.Controls.Button IS mystyle/Button.qml. Therefore mystyle/Button.qml cannot inherit QtQuick.Controls.Button. It cannot inherit itself.

    This is basically the same as writing the following C++:

    // button.h
    #include "button.h"
    class Button : public Button {};
    

    A bit radicalized, but easy to understand analogy. :)

    What you can do is to have (My)Button.qml somewhere, let it inherit QtQuick.Controls.Button, and don't register it as a Qt Quick Controls 2 but simply import the folder. This is what we call as "Customizing Qt Quick Controls 2".