简体   繁体   English

如何使用 C + + QT 获取鼠标坐标?

[英]How to get mouse coordinates with C + + QT?

void Window::acquire(QMouseEvent * event)
{
    pos_xy->setText(QString("coordinates:(%1,%2)").arg(event->pos().x()).arg(event->pos().y()));
}

Window is the inheritance class of QWidget, and the above code is a member function of this class。pos_xy is a QLineEdit *. Window is the inheritance class of QWidget, and the above code is a member function of this class。pos_xy is a QLineEdit *.

i want to get the coordinates of the mouse click,but i don't know how to call the acquire function when the mouse clicked.我想获取鼠标点击的坐标,但我不知道如何在鼠标点击时调用获取 function。

Thanks in advance!提前致谢!

If you want to be notified whenever the user clicks anywhere inside the window, you can implement that behavior using an event filter .如果您想在用户单击 window 内的任何位置时收到通知,您可以使用事件过滤器来实现该行为。 For example, you could create a class like this:例如,您可以像这样创建 class:

#include <QObject>
#include <QMouseEvent>

class MouseWatcher : public QObject
{
public:
   MouseWatcher(QWidget * parent) : QObject(parent) {/* empty */}

   virtual bool eventFilter(QObject * obj, QEvent * event)
   {
      if (event->type() == QEvent::MouseButtonPress)
      {
         QMouseEvent * me = static_cast<QMouseEvent *>(event);
         QPointF windowPos = me->windowPos();
         printf("User clicked mouse at %f,%f\n", windowPos.x(), windowPos.y());
      }
      return QObject::eventFilter(obj, event);
   }
};

... and then install it as a filter on your window object, like this: ...然后将其作为过滤器安装在您的 window object 上,如下所示:

MyWindowObject * win = [...];
MouseWatcher * mw = new MouseWatcher(win);
win->installEventFilter(mw);

... and now it will print the window-relative mouse co-ordinates to stdout every time the user clicks on the window. ...现在,每次用户单击 window 时,它都会将相对于窗口的鼠标坐标打印到标准输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM