2010-12-04 71 views
0

在QLabel中獲得mousePressedEventpos的最佳方式(最簡單)是什麼? (或者基本上只是獲得點擊鼠標相對於位置的QLabel部件)在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; 
} 

不過,我收到編譯錯誤invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*'就行了,我嘗試聲明me。任何想法我在這裏做錯了嗎?

回答

6

您可以繼承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()就會更直接。

+0

你真的需要2個`const`來聲明我嗎?如果是這樣,爲什麼?另外,我在編譯代碼時遇到了問題,因爲編譯器會給我提供`'QEvent *'類型的無效static_cast在該行上鍵入'const QMouseEvent *' – wrongusername 2010-12-04 19:02:17

0

我有同樣的問題

無效的static_cast ...

我只是忘了,包括頭:#include "qevent.h"

現在一切都運作良好。