Important: Please read the Qt Code of Conduct -

Help to understand the necessity of this "import" statement in modified flatstyle example

  • Hi there,
    I am new to QML and I tried to create a custom style and custom components based on the flatstyle example:

    Running this example shows that the custom components in the "Flat" directory (e.g. Flat/Button.qml) are being used. So far so good. However, if I rename the Button component in the MainForm.ui.qml to TheButton and rename the corresponding qml-file in the Flat directory accordingly (i.e. Button.qml -> TheButton.qml), I get the error "TheButton is not a type" when running the application.
    This can be avoided by adding an import "Flat" to the MainForm.ui.qml, but I am wondering why this is necessary (only after renaming)?

    Can anyone enlighten me or give me some pointers to relevant documentation?
    Thanks in advance.

  • The example specifies the Flat directory as a Qt Quick Controls 2 style in the :/qtquickcontrols2.conf configuration file:


    That way, Qt Quick Controls 2 literally registers Flat/Button.qml as the Button type, so it is available via the QtQuick.Controls 2.x import. See Creating a Custom Style for more details.

  • @jpnurmi Thanks for your reply. So if I understand correctly a new component (TheButton) would have to be defined separately somewhere else and in the Flat directory I could redefine it for the Flat style? Or can I only apply the custom style to components defined in QtQuick.Controls 2.x?

  • You can create a new TheButton QML type (TheButton.qml) basically anywhere you want, but for the sake of clarity, you might not want to mix it with the Qt Quick Controls 2 style.

    For your own custom types, such as TheButton, normal QML import rules apply. If TheButton.qml is in the same folder, no import is needed at all. For example, with the following structure, main.qml can create an instance of TheButton without having to import anything.

    |___ main.qml
    |___ TheButton.qml

    However, if TheButton.qml is in a different folder, the folder needs to be imported. For example, if the structure was as follows, main.qml would have to import "TheControls" to be able to create an instance of TheButton.

    |___ main.qml
    |___ TheControls/
         |___ TheButton.qml

  • @jpnurmi Ok, and if I have defined TheButton somewhere and imported it correctly, could I then create another THeButton.qml in the Flat folder to define its looks in the Flat style or is that only possible for default controls? Thanks a lot!

  • The styling system in Qt Quick Controls 2 looks up and registers only known types. However, the styling system is based on file selectors, which you can use to build/select your own styled types.

  • @jpnurmi Great, thanks for your help!