qtqml

Inline/same file object type definition


I can define object type like so:

// Test.qml
import QtQuick 2.6

Rectangle {
    width: 50
    height: 50
}

and easily reuse with set properties like color

// main.qml
import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Test {
        color: "blue"
    }

    Test {
        x:50
        color: "red"
    }
}

But sometimes I have object that I would like to reuse only in a single file. So creating additional file for object that I would only reuse in that single file doesn't seem right.

Can Something similar shown in the example above be done in the same file?


Solution

  • Can Something similar shown in the example above be done in the same file?

    This question seems similar to this one. You can use Loader or dynamic object creation, but I don't think that's better than moving the code to a separate file, as you've done in your example.

    So creating additional file for object that I would only reuse in that single file doesn't seem right.

    I disagree with this. It's still a benefit to reuse a component even if the reuse occurs in a single file. It's much clearer to read code that directly instantiates component instances rather than using loaders or dynamic object creation.