I'm writing a QML extension plugin and I'm looking for a way to access the size of the element I've just implemented.
Right now the new element (named CustomElement
) can be created with any size the user wants to by defining it's width and height values, so on a QML file the user can do:
CustomElement
{
id: my_elem
width: 800
height: 600
}
But I would like to be able to retrieve the size information when the user configures the size through an anchor
, like this:
Rectangle
{
width: 800
height: 600
CustomElement
{
id: my_elem
anchors.fill: parent
}
}
I have no idea how to access anchors
information.
The plugin class is defined as:
class CustomElement: public QDeclarativeItem
{
Q_OBJECT
//Q_PROPERTY() stuff
public:
// ...
};
In the constructor of the plugin, I set QGraphicsItem::ItemHasNoContents
to false:
CustomElement::CustomElement(QDeclarativeItem* parent)
: QDeclarativeItem(parent)
{
qDebug() << "CustomElement::CustomElement parent is:" << parent;
setFlag(QGraphicsItem::ItemHasNoContents, false);
}
After adding the debug, I noticed that the parent
is 0
, which explains why I'm not able to retrieve useful information with boundingRect()
and others methods. Apparently, the problem is that my plugin has no parent. How do I solve this issue?
Solved.
Reading When is the parent set? helped me to find what I needed to do. This plugin is a graphical component (i.e. has a visual interface) meaning it will be draw on screen at some point. When Qt finishes loading your component, it calls a method named componentComplete()
to notify you of so.
All I had to do was add this method to my 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 method of the superclass seems to set the parent of my plugin, and this gives me access to the information set by anchors.fill: parent
.
Then all I had to do retrieve this information was:
Q_Q(Video);
qDebug() << "CustomElement::play: widget size is " << q->width() << "x" << q->height();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With