获取 QLabel 中鼠标单击的位置
在 QLabel 中获取 mousePressedEvent
的 pos
的最佳(最简单)方法是什么? (或者基本上只是获取相对于 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;
}
但是,我收到编译错误 invalid static_cast from type 'QEvent *' 以在我尝试声明
。你知道我在这里做错了什么吗?me
的行上键入“const QMouseEvent*”
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
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;
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以子类化 QLabel 并重新实现 mousePressEvent(QMouseEvent*)。或者使用事件过滤器:
事件过滤的优点是更灵活并且不需要子类化。但是,如果您无论如何都需要因接收到的事件而产生自定义行为,或者已经有一个子类,那么重新实现 fooEvent() 会更直接。
You could subclass QLabel and reimplement mousePressEvent(QMouseEvent*). Or use an event filter:
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().
我有同样的问题
我只是忘记包含标头:
#include "qevent.h"
现在一切正常。
I had the same problem
I just forgot to include the header:
#include "qevent.h"
Now everything is working well.