问题描述
在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中获得鼠标点击的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!