在QLabel中获得鼠标点击的位置 [英] Getting position of mouse click in a QLabel

查看:2726
本文介绍了在QLabel中获得鼠标点击的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在QLabel中获取 mousePressedEvent pos 最好的(最简单的) (或基本上只是获得鼠标点击相对于QLabel小部件的位置)

What is the best (as in simplest) way to obtain the pos of a mousePressedEvent in a QLabel? (Or basically just obtain the location of a mouse click relative to a QLabel widget)

EDIT

我试过Frank建议这样:

I tried what Frank suggested in this way:

bool MainWindow::eventFilter(QObject *someOb, QEvent *ev)
{
if(someOb == ui->label && ev->type() == QEvent::MouseButtonPress)
{
    QMouseEvent *me = static_cast<QMouseEvent *>(ev);
    QPoint coordinates = me->pos();
    //do stuff
    return true;
}
else return false;
}

但是,我收到编译错误 invalid static_cast from在尝试声明 me 的行上键入'QEvent *'以键入'const QMouseEvent *'

However, I receive the compile error invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*' on the line where I try to declare me. Any ideas what I'm doing wrong here?

推荐答案

您可以继承QLabel并重新实现mousePressEvent(QMouseEvent *)。或使用事件过滤器:

You could subclass QLabel and reimplement mousePressEvent(QMouseEvent*). Or use an event filter:

bool OneOfMyClasses::eventFilter( QObject* watched, QEvent* event ) {
    if ( watched != label )
        return false;
    if ( event->type() != QEvent::MouseButtonPress )
        return false;
    const QMouseEvent* const me = static_cast<const QMouseEvent*>( event );
    //might want to check the buttons here
    const QPoint p = me->pos(); //...or ->globalPos();
    ...
    return false;
}


label->installEventFilter( watcher ); // watcher is the OneOfMyClasses instance supposed to do the filtering.

事件过滤的优点是更灵活,不需要子类化。但是如果你需要自定义行为作为接收到的事件的结果或已经有一个子类,它更直接的重新实现fooEvent()。

The advantage of event filtering is that is more flexible and doesn't require subclassing. But if you need custom behavior as a result of the received event anyway or already have a subclass, its more straightforward to just reimplement fooEvent().

这篇关于在QLabel中获得鼠标点击的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆