Aquarius_Girl
Aquarius_Girl

Reputation: 22906

How to make Loader's component the parent of some QtQuick' object?

import QtQuick 2.8
import QtQuick.Window 2.2

import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4
import QtQuick.Controls 2.1

Window
{
    id: head
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Loader
    {
        id: loader
     }

     Component
     {
          id: rect

          Window
          {
              id: ppp

              visible: true
              width: 164
              height: 148
              title: qsTr("Hello World")
          }
     }

    Rectangle
    {
        anchors.fill: parent
        color: "blue"
        Rectangle
        {
            id: leftArea

            height: 100
            width:  100
            color: "red"

            MouseArea
            {
                anchors.fill: parent
                onClicked:
                {
                    loader.sourceComponent = rect
                    leftArea.parent = loader
                }
            }
        }
   }

When I click on that rectangle, it disapears but it doesn't get shown in the loader's window. Moreover when I maximize the new resultant window the GUI hangs.

Aim is to make the new Loader's window the parent of the rectangle on click.

Upvotes: 0

Views: 45

Answers (1)

JarMan
JarMan

Reputation: 8277

There's two issues with your code.

  1. You should be using parent = loader.item, not parent = loader. You don't want the Loader to be your parent, but the item that it has loaded.
  2. The Component that you're adding to the Loader is a Window, which is not a QQuickItem. You will get an error when trying to assign a Window as the visual parent of an Item. You can get around that by creating an Item inside the window and exposing that through a property using Window's contentItem property, like this:
    Loader
    {
        id: loader
     }

     Component
     {
          id: rect

          Window
          {
              id: ppp

              visible: true
              width: 164
              height: 148
              title: qsTr("Hello World")
          }
     }

    Rectangle
    {
        anchors.fill: parent
        color: "blue"
        Rectangle
        {
            id: leftArea

            height: 100
            width:  100
            color: "red"

            MouseArea
            {
                anchors.fill: parent
                onClicked:
                {
                    loader.sourceComponent = rect
                    leftArea.parent = loader.item.contentItem
                }
            }
        }
   }

Upvotes: 2

Related Questions