wro*_*ame 0 c++ qt point-of-sale mousepress
在QLabel中获得pos
a 的最佳(最简单)方法mousePressedEvent
是什么?(或者基本上只获取相对于QLabel小部件的鼠标点击位置)
编辑
我尝试了Frank以这种方式建议的内容:
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;
}
Run Code Online (Sandbox Code Playgroud)
但是,我invalid static_cast from type 'QEvent*' to type 'const QMouseEvent*'
在我尝试声明的行上收到编译错误me
.我在这里做错了什么想法?
您可以继承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.
Run Code Online (Sandbox Code Playgroud)
事件过滤的优点是更灵活,不需要子类化.但是如果你因为接收到的事件而需要自定义行为或者已经有了子类,那么重新实现fooEvent()会更直接.