Read the size of the QML element determined by anchors.fill: parent

I am writing a QML extension plugin and I am looking for a way to access the size of an element that has just been implemented.

Now a new element (named CustomElement ) can be created with any size that the user wants by defining the values โ€‹โ€‹of width and height , so on a QML file that the user can make:

 CustomElement { id: my_elem width: 800 height: 600 } 

But I would like to get size information when the user adjusts the size using anchor , for example:

 Rectangle { width: 800 height: 600 CustomElement { id: my_elem anchors.fill: parent } } 

I do not know how to access anchors information.

The plugin class is defined as:

 class CustomElement: public QDeclarativeItem { Q_OBJECT //Q_PROPERTY() stuff public: // ... }; 

In the plugin constructor, I set QGraphicsItem::ItemHasNoContents to false:

 CustomElement::CustomElement(QDeclarativeItem* parent) : QDeclarativeItem(parent) { qDebug() << "CustomElement::CustomElement parent is:" << parent; setFlag(QGraphicsItem::ItemHasNoContents, false); } 

After adding debugging, I noticed that parent is 0 , which explains why I cannot get useful information using the boundingRect() and others methods. Apparently the problem is that my plugin does not have a parent. How to solve this problem?

+7
source share
1 answer

solvable .

Reading When is the parent set? helped me find what I needed to do. This plugin is a graphical component (that is, it has a visual interface), which means that at some point it will draw on the screen. When Qt finishes loading your component, it calls a method called componentComplete() to notify you of this.

All I had to do was add this method to the class definition as a public method:

 virtual void componentComplete(); 

and implement it as:

 void CustomElement::componentComplete() { Q_D(CustomElement); // Call superclass method to set CustomElement() parent QDeclarativeItem::componentComplete(); } 

Calling the superclass method seems to set the parent element of my plugin, and this gives me access to the information given by anchors.fill: parent .

Then all I had to get was get this information:

 Q_Q(Video); qDebug() << "CustomElement::play: widget size is " << q->width() << "x" << q->height(); 
+5
source

All Articles