[Solved]X-y coordinates of a button press
-
wrote on 21 Nov 2013, 19:45 last edited by
Is there anyway that I can tell where the position of the mouse is on a button when it is clicked?
I would like to read the x y position of the mouse the moment the button is clicked. -
Hi
You can subclass the button base class, overload mousePressEvent and get the position from the give QMouseEvent. Or install an event filter on the button and check for a QEvent::MouseButtonPress on it.
Hope it helps
-
wrote on 21 Nov 2013, 20:02 last edited by
How would I implement QMouseEvent::x(); with a button click?
-
wrote on 21 Nov 2013, 20:21 last edited by
Maybe this might be usefull: "const QPointF & QMouseEvent::localPos() const":http://qt-project.org/doc/qt-5.0/qtgui/qmouseevent.html#localPos
?with best regards,
Robert -
wrote on 21 Nov 2013, 22:14 last edited by
this is what I have.
void MainWindow::on_pushButton_clicked()
{
QMouseEvent *mouseEvent;
qDebug() << QString::number(mouseEvent->pos().x());
qDebug() << QString::number(mouseEvent->pos().y());
}and all I get is "0" on the output
-
That won't work, you're not inside an event handler or a more specialized mouse event handler.
Technically this code will also crash.
-
wrote on 22 Nov 2013, 11:09 last edited by
As SGaist wrote "here":http://qt-project.org/forums/viewthread/35153/#151578 You have 2 options:
- Derive Your button from QPushButton class and reimplement there mousePressEvent(QMouseEvent * e) "doc":http://qt-project.org/doc/qt-5.0/qtwidgets/qabstractbutton.html#mousePressEvent
- Implement and set event filter on Your button "Event filter":http://qt-project.org/doc/qt-4.8/eventsandfilters.html#event-filters
When You receive interesting event (here: QMouseEvent) You will be able to get exact position of mouse press.
If You still need some help us know :)
with best regards,
Robert -
wrote on 25 Nov 2013, 12:59 last edited by
Thanks poorBob,
Im not going to lie, I am learning as I go and I don't even know where to begin here. I read up on the links, and I am still a little lost.is this the right function call?
void QAbstractButton::mousePressEvent(QMouseEvent *e){}:
and then what do I do with "e"? what syntax gets me the pos?Sorry but Im new to all this GUI Stuff lol!
-
wrote on 25 Nov 2013, 13:55 last edited by
@void MainWindow::on_pushButton_clicked()
{
qDebug()<<ui->pushButton->cursor().pos();//screen coordinates
qDebug()<<ui->pushButton->mapFromGlobal(ui->pushButton->cursor().pos());//local coordinates}@
-
wrote on 25 Nov 2013, 14:01 last edited by
Thank you Nicu!! Works perfectly!!
5/10