4

I have just started playing with QML and have a view where I have a bunch of components as follows:

Window {
    ....
    property Component dateTumbler: ControlView {
        // Definition follows
    }

    property Component timeTumbler: ControlView {
       // More definition follows
    }

    // More controls
}

This makes the main QML file very long and cumbersome to edit and maintain. I tried to separate this into different files as follows:

// DateTumblerView.qml
component: DateTumblerView { // Not sure how to inherit here..
    // Definition here
}

I'm trying to use it like this:

property component dateTumbler: DateTumblerView {}

However, this never works and the DateTumblerView is never found. I am not sure if I am doing this correctly.

[EDIT] ControlView is defined as follows:

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtMultimedia 5.5

Rectangle {
    id: view
    property bool darkBackground: false

    Text {
        id: textSingleton
    }

    SoundEffect {
        id: playCalSound
        source: "qrc:/sound/test.wav"
    }
}

[END EDIT]

What is the proper way to split QML code into multiple files?

Luca
  • 10,458
  • 24
  • 107
  • 234

1 Answers1

8

Your DateTumblerView.qml file should look like this:

ControlView {
   // More definition follows
}

And you would use it like this:

property Component dateTumbler: DateTumblerView {}

Or:

Component {
    id: dateTumbler

    DateTumblerView {}
}

Or if you wanted to use it directly:

DateTumblerView {}

It's pretty much the same as when your code was just in one file. Anytime you do <Type> {}, you're inheriting that type and can set or add new properties, functions, and subcomponents. The difference is that it is in a separate file, has a specific name (the name of the file), and you can reuse that code as many times as you want.

For more details, see Defining Custom QML Types for Re-use.

iBelieve
  • 1,502
  • 17
  • 32
  • Thanks for the answer. I tried doing that and it complains that ControlView is not a type. I am adding the definition of ControlView to my original post – Luca Feb 01 '16 at 08:02
  • Disregard my last comment...that happened because I cannot spell. need my first coffee... – Luca Feb 01 '16 at 08:35