Reputation: 5040
Qt 5.10.1 under Windows 7. I'm trying to anchor some Components inside an Item with margins defined. I mean, I want to anchor taking in account for margins.
My code:
Item {
width: parent.width
anchors.margins: 100
Rectangle {
width: 50
height: 50
anchors.right: parent.right
}
}
I would expect the Rectangle will be positioned on the right side but 100 px from the edge. Instead it's placed just to the edge.
Of course I can add:
anchors.rightMargin: 100
but I have to do this manually for each children of the main Item. I wonder if there's a way to anchor taking care of existing margins.
Upvotes: 3
Views: 3610
Reputation: 2051
If I understand well, your problem is not the position of the Rectangle
but the position of the parent Item
.
Since you define the width
of the Item instead of using explicit anchors, the margins has no effect.
Try to position the Item using anchors instead of width:
Item {
anchors.fill: parent
anchors.margins: 100
Rectangle {
width: 50
height: 50
anchors.right: parent.right
}
}
The Item
will be correctly positionned 100px from its parent and the Rectangle
will be positionned at the edge of the Item
.
Note that there is no "CSS padding - like" behavior in QML: you have to explicitely define in each child component how it fills the parent.
Edit (following your comment):
If using inside a Row
or Column
, as far as I know the only solution is to specify a rightMargin
in every child.
About padding:
Padding does not exist in QML (except for Qt Quick Controls 2 components): declaring an item as a child of another item does not mean that it is visually located inside its parent. Thus the only way to position an element is by using anchors
on every child.
If you want to simulate a padding in the parent item you can define it as a property
and use it in every child:
Item {
readonly property int padding: 100
width: parent.width
height: parent.height
Rectangle {
width: 50
height: 50
anchors {
right: parent.right
margins: parent.padding
}
}
}
Or wrap the children in another Item
:
Item {
width: parent.width
height: parent.height
Item {
anchors.fill: parent
anchors.rightMargin: 100
Rectangle {
width: 50
height: 50
anchors.right: parent.right
}
}
}
Upvotes: 4