bool ItemWidget::filterMouseEvents(QTextEdit *edit, QEvent *event) { QEvent::Type type = event->type(); switch (type) { case QEvent::MouseButtonPress: case QEvent::MouseButtonDblClick: { QMouseEvent *e = static_cast<QMouseEvent*>(event); if ( !canMouseInteract(*e) ) e->ignore(); else if (e->button() == Qt::LeftButton) edit->setTextCursor( edit->cursorForPosition(e->pos()) ); break; } case QEvent::MouseMove: { QMouseEvent *e = static_cast<QMouseEvent*>(event); if ( !canMouseInteract(*e) ) e->ignore(); break; } case QEvent::MouseButtonRelease: { QMouseEvent *e = static_cast<QMouseEvent*>(event); if ( canMouseInteract(*e) && edit->textCursor().hasSelection() ) edit->copy(); e->ignore(); break; } default: return false; } Qt::TextInteractionFlags flags = edit->textInteractionFlags(); if (event->isAccepted()) flags |= Qt::TextSelectableByMouse; else flags &= ~Qt::TextSelectableByMouse; edit->setTextInteractionFlags(flags); return false; }
bool ItemWidget::filterMouseEvents(QTextEdit *edit, QEvent *event) { const auto type = event->type(); bool allowMouseInteraction = true; switch (type) { case QEvent::Enter: edit->setMouseTracking(true); edit->viewport()->setCursor( QCursor() ); return false; case QEvent::MouseButtonPress: case QEvent::MouseButtonDblClick: { QMouseEvent *e = static_cast<QMouseEvent*>(event); if ( !canMouseInteract(*e) ) allowMouseInteraction = false; else if (e->button() == Qt::LeftButton) edit->setTextCursor( edit->cursorForPosition(e->pos()) ); break; } case QEvent::MouseMove: { QMouseEvent *e = static_cast<QMouseEvent*>(event); if ( !canMouseInteract(*e) ) allowMouseInteraction = false; break; } case QEvent::MouseButtonRelease: { QMouseEvent *e = static_cast<QMouseEvent*>(event); if ( canMouseInteract(*e) && edit->textCursor().hasSelection() ) edit->copy(); allowMouseInteraction = false; break; } default: return false; } Qt::TextInteractionFlags flags = edit->textInteractionFlags(); if (allowMouseInteraction) { flags |= Qt::TextSelectableByMouse; flags |= Qt::LinksAccessibleByMouse; } else { flags &= ~Qt::TextSelectableByMouse; flags &= ~Qt::LinksAccessibleByMouse; } edit->setTextInteractionFlags(flags); if (type == QEvent::MouseButtonPress || type == QEvent::MouseMove) { const auto e = static_cast<QMouseEvent*>(event); if (allowMouseInteraction) { const auto anchor = edit->anchorAt(e->pos()); if ( anchor.isEmpty() ) { edit->viewport()->setCursor( QCursor(Qt::IBeamCursor) ); } else { edit->viewport()->setCursor( QCursor(Qt::PointingHandCursor) ); if (type == QEvent::MouseButtonPress) { QDesktopServices::openUrl( QUrl(anchor) ); e->accept(); return true; } } } else { edit->viewport()->setCursor( QCursor() ); } } return false; }