Align new window to existing widget
-
I wasn't able to find any way to set the window position, to fit the another widget.
I want to spawn a window,at the center of particular widget.Can't also find a way to get the screen coordinates of the widget, i tried pos(), and then use setGeometry(), but the results are terrible, even when i set all the parameters as the function requires.
setGeometry(x, y, width, height) and it still doesn't work.
At x and y, i put the target widget position i got from pos(), the rest is current widget width and height.What is wrong with it? This system is absolutely terrible, completely counterintuitive.
-
First of all make sure you're familiar with the Window Geometry concepts.
For top level widgets
pos()is the screen coordinate of the window frame. For widgets that have parentspos()is the position of the top left corner in parent coordinates.To position a window in the center of a particular widget first make sure it has correct dimensions. Windows don't have a correct size until they are first shown or the size is set explicitly, so make sure you do that. Then take the rect of the widget, get its center and translate that to the screen coordinates.
So for a new window of size 200x200 something like this:
QPoint old_center = old_widget->mapToGlobal(old_widget->rect().center()); QRect new_geometry(old_center - QPoint(100,100), QSize(200,200)); new_widget->setGeometry(new_geometry); new_widget->show();Another way is to first calculate the position in old widget's coordinates and then translate them to screen coordinates. Different formula, same result.
QRect new_geometry(0, 0, 200, 200); QPoint pos_in_old_coord = QPoint(old_widget->width() - new_geometry.width(), old_widget->height() - new_geometry.height()) / 2; new_geometry.translate(old_widget->mapToGlobal(pos_in_old_coord)); new_widget->setGeometry(new_geometry); new_widget->show();