【问题标题】:Getting position of mouse click in a QLabel在 QLabel 中获取鼠标点击的位置
【发布时间】:2010-12-04 10:58:24
【问题描述】:

在 QLabel 中获得mousePressedEventpos 的最佳(最简单)方法是什么? (或者基本上只是获取鼠标点击相对于 QLabel 小部件的位置)

编辑

我尝试了弗兰克的建议:

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;
}

但是,我在尝试声明 me 的行上收到编译错误 invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*'。有什么想法我在这里做错了吗?

【问题讨论】:

    标签: c++ qt point-of-sale mousepress


    【解决方案1】:

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

    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() 会更直接。

    【讨论】:

    • 你真的需要2个const在我的声明中吗?如果是这样,为什么?另外,我在编译你的代码时遇到了麻烦,因为编译器在那一行给了我invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*'
    • 您是否包括了 ? const 并不是绝对必要的,但我认为将临时变量设为 const 是一种很好的做法。
    • 啊,是的,我没有包括那个。谢谢!我想知道的是为什么不只是 const QMouseEvent * me... 第二个 const 做什么?
    • 第一个 const 使对象为 const,第二个使指针本身为 const。
    【解决方案2】:

    我遇到了同样的问题

    无效的静态转换...

    我只是忘了包含标题:#include "qevent.h"

    现在一切正常。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2015-02-18
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多