Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

qt

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??

like image 966
skg Avatar asked Sep 10 '12 11:09

skg


People also ask

What is an object in Qt?

This is the object for which the wizard created the class and the UI file. The user interface contains visual elements that are called widgets in Qt. Examples of widgets are text edits, scroll bars, labels, and radio buttons. A widget can also be a container for other widgets; a dialog or a main application window, for example.

How to get the position of widgets in Qtable widget?

@Bonnie said in How to get the position of widgets in QTablewidget: @MasterBlade You need to map pos from comboBox to the tableWidget (maybe it's better to map to the viewport) using QPoint QWidget::mapTo ( const QWidget * parent, const QPoint &pos) const

How do I get the exact position of a widget?

To get the exact position of a widget, we need to give it a key. To make it easier to understand, see the following example. This sample app contains an amber box and a floating button. Once the user presses the button, we’ll calculate then display the X and Y coordinates of the box on the screen.

How do I create a notepad widget in Qt?

In the Class Information dialog, type Notepad as the class name and select QMainWindow as the base class. The Qt Widgets Application wizard creates a project that contains a main source file and a set of files that specify a user interface (Notepad widget):


3 Answers

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

like image 68
Ahmad Mushtaq Avatar answered Oct 23 '22 01:10

Ahmad Mushtaq


In Qt5 this also works

QTabBar *widget =(QTabBar*) qApp->widgetAt(QCursor::pos());
like image 21
Yash Avatar answered Oct 23 '22 01:10

Yash


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.

like image 36
Bart Avatar answered Oct 23 '22 00:10

Bart