Results 1 to 3 of 3

Thread: set parent when creating a QML component from C++

  1. #1
    Join Date
    Nov 2014
    Posts
    33
    Thanks
    1
    Qt products
    Qt5
    Platforms
    Windows Android

    Default set parent when creating a QML component from C++

    Hello,

    I've a QML component that is created from C++ code:

    QML code:
    Qt Code:
    1. Rectangle {
    2. width: parent.width
    3. y: parent.height / 2
    4. color: "red"
    5. }
    To copy to clipboard, switch view to plain text mode 

    Qt Code:
    1. QQmlComponent component(engine, QUrl(src));
    2. QObject *comp = component.create();
    3. QQuickItem *item = qobject_cast<QQuickItem*>(comp);
    4. item->setParentItem(root);
    To copy to clipboard, switch view to plain text mode 

    When the component is created appears these errors:

    TypeError: Cannot read property 'height' of null
    TypeError: Cannot read property 'width' of null

    On creation, the parent property is null and not is valid until the item->setParentItem is executed. How can I set the parent item when creating the component? or how to avoid these errors?

    Best regards.

  2. #2
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,416
    Thanks
    37
    Thanked 1,544 Times in 1,494 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: set parent when creating a QML component from C++

    Have you tried a condition on parent?

    Qt Code:
    1. width: parent ? parent.width : 0
    To copy to clipboard, switch view to plain text mode 

    Cheers,
    _

  3. The following user says thank you to anda_skoa for this useful post:

    lqsa (10th January 2016)

  4. #3
    Join Date
    Nov 2014
    Posts
    33
    Thanks
    1
    Qt products
    Qt5
    Platforms
    Windows Android

    Default Re: set parent when creating a QML component from C++

    It works! Thank you very much.

Similar Threads

  1. Creating a dynamic QML component from a non Qt thread
    By Valerian in forum Qt Programming
    Replies: 3
    Last Post: 5th July 2015, 13:30
  2. Replies: 0
    Last Post: 10th August 2012, 18:16
  3. Replies: 5
    Last Post: 21st April 2010, 21:36
  4. Replies: 2
    Last Post: 4th February 2010, 06:54
  5. Replies: 1
    Last Post: 15th June 2009, 17:22

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.