Qt How to find an object in widgets using positions x () and y ()

I have MainWindow. On MainWindow, I have several Qlabel. Now I need to find QLabel. Using MousePressEvent, I can get the X () and Y () position of the mouse click.

How can I use this coordinate to identify QLabel ??

Is there any function in QT to find an object clicked using the X () and Y () coordinates?

+8
qt
source share
4 answers

Since QLabel is a subclass of QWidget, you can handle mouse click events in QLabel :: mousePressEvent

virtual void mousePressEvent ( QMouseEvent * ev ) 

But in QMainWindow you can use childAt to get child widgets in x, y

 QWidget * QWidget::childAt ( int x, int y ) const QLabel* label= static_cast<QLabel*>(mainWindow->childAt(x,y)); 

More details: http://doc.qt.io/qt-5/qwidget.html#childAt

+9
source share

In Qt5, this also works.

 QTabBar *widget =(QTabBar*) qApp->widgetAt(QCursor::pos()); 
+4
source share

Use widgetAt function inside QApplication

 QWidget *widget = qApp->widgetAt(x,y); 

which can then be dynamic_cast in QLabel .

+1
source share

Instead of trying to determine which label the mouse coordinates clicked on, you can also use mousePressEvent() labels.

For example, make your own overloaded shortcut class and on mousePressEvent() emit a clicked() signal, which you can then bind to the slot.

+1
source share

All Articles