3

Both can create objects dynamically.
When should Loader be preferred over Qt.createQmlObject and vice versa in QML?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

4

The Loader can be regarded as a placeholder for a particular object. It also gives you the ability to reference the underlying object through the Loader's id.

Qt.createQmlObject is generally more powerful than a Loader, because you can instantiate as many objects as you want, and also it doesn't have the overhead of the Loader. But you have to take care to keep track of what you create in order to be able to reference it.

The other functions Qt.createComponent() and then createObject() offer similar advantages, plus the possibility to pass properties to be used in the object's creation instead of setting them only after it has been created.

I personally see very little point in Loader and rarely use it, if at all in production code. IMO it was introduced for the sake of the "non-programmer" much like most of the recent development, such as the new designer and QML .ui files, which I find kind of annoying, but it is understandable - trying to increase adoption by non-programmers.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
dtech
  • 47,916
  • 17
  • 112
  • 190
  • 1
    Very little point in `Loader`? Have you ever built a real QQ2 application, with hundreds of source files? Hiding invisible screens behind `Loader`s makes your app appear on screen in 1 second instead of 10 seconds. – peppe Mar 10 '15 at 22:44
  • @peppe the `Loader` does no magic, it is no faster than dynamically instantiating objects, but it is heavier. In apps with lots of components I pre-load and keep the components in memory to instantiate faster. If you can do dynamic object instantiation right, `Loader` is just overhead and source pollution. Furthermore `Loader` has nothing to do with "invisible screens", whatever those might be. If by that you mean invisible component sitting idle - that just wastes memory, IMO modern hardware is fast enough to make CPU cycles a good investment to save memory, especially on mobile devices. – dtech Mar 10 '15 at 23:10
  • I didn't say it does magic, I said that the dynamic instantiation offered by `Loader` is a thing used in any non-trivial QQ2 application. – peppe Mar 11 '15 at 08:35
  • And I said "**I personally** see very little point in `Loader`" - your experience may vary. – dtech Mar 11 '15 at 12:21
  • `also it doesn't have the overhead of the Loader` Please mention what are the overheads of a Loader with references to your claims. Thanks. – Aquarius_Girl Mar 17 '15 at 08:32
  • @TheIndependentAquarius - each loader is hundreds of bytes, possibly thousands. It also takes time to instantiate like everything else. – dtech Mar 17 '15 at 13:43