Qt 6.5.2 下 QGraphicsView 中使用触控手势的问题
自定义的QGraphicsView 中加入setScene后,其它Gesture能够触发,但 QPanGesture不能在场景中触发。而空白QGraphicsView(QWidget)则可以正常触发PanGesture手势……
源码和文档中都已经说明,gesture是给QGraphicsObject使用的……但我们就是想使用PanGesture手势来操作场景拖动……这可怎么办……
调试源码,发现其qt.widgets.gestures模块的输出没开,找到“C:\Users\用户名\AppData\Local\QtProject”路径,新建qtlogging.ini打开日志输出开关
发现PanGesture被送往了其它QWidget,并未送入QGraphicsView……,当然View的Event、eventFilter也就找不到PanGesture了,而此Widget没有ObjectName、也并非我new出来的,因为怀疑是ViewPort。
对QGraphicsView的viewport()->installFilter(this)
// 注册手势,this为自定义的QGraphicsView this->viewport()->grabGesture(Qt::PanGesture); this->viewport()->grabGesture(Qt::PinchGesture); // 安装事件过滤器 this->viewport()->installEventFilter(this);
事件过滤器如下:
bool StreamControlWidget::eventFilter(QObject* watched, QEvent* event) { // 过滤不必要的鼠标事件。Press Release是为保留点击事件(Qt的单点点击会被转化为鼠标单击事件) if (//event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseMove || //event->type() == QEvent::MouseButtonRelease || event->type() == QEvent::MouseButtonDblClick || event->type() == QEvent::Wheel || //event->type() == QEvent::GraphicsSceneMousePress || event->type() == QEvent::GraphicsSceneMouseMove || //event->type() == QEvent::GraphicsSceneMouseRelease || event->type() == QEvent::GraphicsSceneMouseDoubleClick || event->type() == QEvent::GraphicsSceneWheel) { event->accept(); return true; } if (watched == viewport() && event->type() == QEvent::Gesture) { QGestureEvent* ev = static_cast<QGestureEvent*>(event); if (event->type() == QEvent::Gesture) { return gestureEvent(static_cast<QGestureEvent*>(event)); } return true; } return QWidget::eventFilter(watched, event); }
gestureEvent函数
bool gestureEvent(QGestureEvent* event) { if (QGesture* pch = event->gesture(Qt::PinchGesture)) // 自定义处理 pinchTriggered(static_cast<QPinchGesture*>(pch)); if (QGesture* pan = event->gesture(Qt::PanGesture)) { // 自定义处理 panTriggered(static_cast<QPanGesture*>(pan)); } return true; }
触发正常