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??
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.
@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
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.
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):
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
In Qt5 this also works
QTabBar *widget =(QTabBar*) qApp->widgetAt(QCursor::pos());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With