BabyWolf
BabyWolf

Reputation: 25

Why i cannot see green rectangle in main window?

I can try to use Qt and QML from Python.

main_window.qml:

import QtQuick 2.10

Rectangle {
  id: mainWindow
  objectName: "mainWindow"
  width: 1000
  height: 100
  x: 100
  y: 100
  color: "gray"

  Rectangle {
    id: red
    objectName: "red"
    width: 800
    height: 50
    x: 200
    y: 200
    color: "red"
  }
}

rectangle.qml:

import QtQuick 2.10

Rectangle {
  id: green
  objectName: "green"
  width: 800
  height: 50
  x: 200
  y: 400
  color: "green"
}

test.py:

import os
import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlComponent
from PyQt5.QtQuick import QQuickView

os.environ["QML_DISABLE_DISK_CACHE"] = "true"

class Graphic:
  def __init__(self):
    self.main_window = QQuickView()
    self.main_window.setSource(QUrl.fromLocalFile("ui/main_window.qml"))

  def load_screen(self):
    component = QQmlComponent(self.main_window.engine())
    component.loadUrl(QUrl.fromLocalFile("ui/rectangle.qml"))
    item = component.create()
    item.setParent(self.main_window.rootObject())

    self.main_window.show()

if __name__ == '__main__':
  app = QGuiApplication(sys.argv)
  graphic = Graphic()
  graphic.load_screen()
  app.exec()

It's a simple example for my question. I try dynamicly load and display screens in main window. I see gray and red rectangle, but cannot see the green rectangle. What's wrong?

Upvotes: 1

Views: 60

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

According to the docs:

parent : QQuickItem *

This property holds the visual parent of the item.

Note: The concept of the visual parent differs from that of the QObject parent. An item's visual parent may not necessarily be the same as its object parent. See Concepts - Visual Parent in Qt Quick for more details.

In other words, for an item to be visible, a visual parent must be established through setParentItem():

def load_screen(self):
    component = QQmlComponent(self.main_window.engine())
    component.loadUrl(QUrl.fromLocalFile("ui/rectangle.qml"))
    item = component.create()
    item.setParent(self.main_window.rootObject())
    item.setParentItem(self.main_window.rootObject()) # <---
    self.main_window.show()

enter image description here

Upvotes: 0

Related Questions