How to get the position of the Qt widget in the main window--determine whether the mouse is on a control and the position on the control

When designing programs with Qt Creator, the most convenient is the ui designer, which can easily get the desired layout.

 

But the consequence of this automatic layout is that it is difficult to know the relative position of a component in the window in the main window.

 

It becomes very troublesome when handling mouse events of child windows. The main window has menus, toolbars, etc., if you want to draw with the mouse,

Mapping mouse tracks to widgets, these problems.

 

 

In fact, the most important thing is to get the position of the starting point of the widget relative to the main window.

 

For example: drag a QScrollArea in the main window and place a QLabel on it to display mouse events.

You can see the following structure on the ui object structure.

 

As you know, we can use pos() to get the position of a widget's starting point relative to its parent.

 

Then, looking at the structure, we can see that to get the relative position of scrollArea_2 in the main window (MainWindow)

That is: ui->scrollArea_2->pos()+ui->centralWidget->pos()

 

So I want to get the relative position area of ​​the window ScrollArea_2 in the main window:

 

    labelrect = QRect(ui->scrollArea_2->pos()+ui->centralWidget->pos(),
                      ui->scrollArea_2->size());
 
 

Then to determine whether the mouse is on this control, just write the following statement in the mouse event response function:

if(labelrect.contains(event->pos()))   {……}

 

 

Now you can determine the position of a child widget in an arbitrarily complex ui structure, but be careful:

Parent relationship, that is, the relative position of the current component to its parent component, the relative position of its parent component to the upper component,

until the position relative to the main window.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325388583&siteId=291194637
Recommended