I am working on a project that requires multiple instances to be placed inside a specific area. I am having trouble creating a function that will do that for me. Right now I have to manually set the value for each of the instances. How would I go about making a function that will take all the instances and place them evenly in a circle based on a radius?
Here is the area of code that I have where I manually set the placement. The function setIconWidgetLocation is what I have so far, just do not know what to place inside.
zMenuWidget::zMenuWidget(QWidget *parent) :
QWidget(parent)
{
icon1 = new iconWidget(this);
icon2 = new iconWidget(this);
}
void zMenuWidget::resizeEvent(QResizeEvent *event)
{
int yEndPosition = 0;
int outerRadius = 100;
int innerRadius = 60;
QSizeF size = event->size();
QPointF center(size.width(),size.height());
center /= 2.0;
yEndPosition = (outerRadius - innerRadius)/2.0 + innerRadius;
yEndPosition = center.y() - yEndPosition;
int yCurrIconLoc = icon1->rect().center().y();
int xCurrIconLoc = icon1->rect().center().x();
icon1->move(center.x() - xCurrIconLoc, yEndPosition - yCurrIconLoc);
}
void setIconWidgetLocation(iconWidget* w, float angle)
{
}
I’m fairly certain that this is precisely what
QLayoutis for. You can derive your own class from that and use it to layout its widgets radially.But just going on what you have now, forget that… You just want simple placement. You will need to iterate through all your icons. Presumably you have them stored in an array.
To do this, you need to know the radius of your circle, which seem to have hard-coded. What you probably want is to align your icon centres on the circle, so you need to subtract half the icon size from your outer radius. But I see you have both an outer and inner radius. So let’s just put the icon centres in the middle of that:
And all you’re really doing here is maths. Circles are easy. You decide what angle of arc is subtended for each icon. That’s up to you. You might calculate it so that icons don’t collide, or you might make it constant, or you might evenly space your icons.
But you seem to want evenly-spaced icons, so that’s easy. Each icon occupies a slice of the pie, which in radians is Tau, more traditionally known as 2Pi.
Every circle needs a centre and a radius. Now you just need to decide where to begin. The angle zero is typically on the right (an offset of
radiushorizontally and zero vertically), but you probably want it at the top. We can either add a quarter revolution (Tau/4) or we can just flip the maths.Normally the formula for a circle is:
But if I want to start this at the top (still rotating anti-clockwise), I do this:
Now all that’s left to do is find the centres of all your icons and position them: