bool Widget::event(QEvent *event) { if (event->type()==QEvent::MouseButtonPress) { qDebug()<<"mouse press int event func"; return true; } else { return QWidget::event(event); } } void Widget::mousePressEvent(QMouseEvent *event) { qDebug()<<"mouse press event func"; }这段代码为什么在event函数中没有起到拦截鼠标点击事件的作用,还是会执行mousePressEvent函数
时间: 2024-02-13 22:07:26 浏览: 25
如果您的代码仍然无法拦截鼠标点击事件并阻止其继续传递,可能是因为您的 `Widget` 对象没有设置 `Qt::WA_AcceptTouchEvents` 标志。在某些情况下,Qt 会将触摸事件转换为鼠标事件,并且只有设置了 `Qt::WA_AcceptTouchEvents` 标志的窗口才能接收到触摸事件。
您可以通过以下方式设置 `Qt::WA_AcceptTouchEvents` 标志:
```
setAttribute(Qt::WA_AcceptTouchEvents);
```
这样,您的 `Widget` 对象就可以接收到触摸事件,并且在 `event` 函数中可以拦截鼠标点击事件并阻止其继续传递,而不会调用 `mousePressEvent` 函数。
相关问题
bool Widget::event(QEvent *event) { if (event->type()==QEvent::MouseButtonPress) { qDebug()<<"mouse press int event func"; } else { return QWidget::event(event); } }为什么在event函数中没有起到拦截鼠标点击事件的作用
在代码中,当鼠标点击事件发生时,程序会进入到 `if` 语句中,并输出 "mouse press int event func",但是在 `if` 语句中并没有任何处理,因此事件会被直接处理掉而不会被拦截。
如果您希望在处理完事件后阻止其继续传递,可以将函数返回值设置为 `true`。因此,您需要在 `if` 语句中添加处理代码,并在处理完事件后返回 `true`,以防止事件继续传递,例如:
```
bool Widget::event(QEvent *event) {
if (event->type()==QEvent::MouseButtonPress)
{
qDebug()<<"mouse press int event func";
// 在此添加处理代码
return true;
}
else
{
return QWidget::event(event);
}
}
```
这样就可以拦截鼠标点击事件并进行处理了。
但我的案例中已经对event函数中的返回值定义为true
是的,你的代码中在处理鼠标按下事件时,`event` 函数返回了 `true`,表示该事件已经被处理。但是,`event` 函数并不会阻止事件的传递,而是告诉上层调用者该事件已经被处理了。如果你想完全阻止事件传递,可以在 `event` 函数中同时返回 `true` 和 `false`,表示该事件已经被处理,并且不再需要继续传递。例如,可以这样修改代码:
```
bool MyLabel::event(QEvent *e) {
if (e->type() == QEvent::MouseButtonPress) {
qDebug() << "mylabel event对鼠标点击事件进行处理" << endl;
return true; // 事件已经被处理,并停止继续传递
}
return QLabel::event(e); // 其他事件继续传递给父类处理
}
```
这样,当事件类型为鼠标按下事件时,`event` 函数返回 `true`,表示该事件已经被处理,并且不再需要继续传递。而对于其他事件,`event` 函数调用 `QLabel` 的 `event` 函数处理,保证了事件能够正常传递。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)