skg
skg

Reputation: 948

Qt How to Find Object on a widget using x() and y() position

I have a MainWindow. On MainWindow I have multiple Qlabel's. Now, i need to find the QLabel clicked. Using MousePressEvent, i can get the X() and Y() position of the mouse clicked.

How can i use this Co-ordinate to identify the QLabel??

Is there any function in QT to find the Object clicked using X() and Y() co-ordinate??

Upvotes: 10

Views: 13254

Answers (4)

Ahmad Mushtaq
Ahmad Mushtaq

Reputation: 1395

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

virtual void mousePressEvent ( QMouseEvent * ev )

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

QWidget * QWidget::childAt ( int x, int y ) const

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

Read more at: http://doc.qt.io/qt-5/qwidget.html#childAt

Upvotes: 13

Yash
Yash

Reputation: 7064

In Qt5 this also works

QTabBar *widget =(QTabBar*) qApp->widgetAt(QCursor::pos());

Upvotes: 4

Bart
Bart

Reputation: 20048

Rather than trying to identify which label has been clicked on from mouse coordinates, you could also alternatively use a label's mousePressEvent() method.

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

Upvotes: 2

ismail
ismail

Reputation: 47682

Use the widgetAt function inside QApplication

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

which then you can dynamic_cast into QLabel.

Upvotes: 1

Related Questions