我有一个QGraphicsView
和一个QGraphicsScene
,我启用了
this->setDragMode(QGraphicsView::RubberBandDrag);
用于橡皮筋选择。但是,在我的应用程序中,您需要按下 CTRL 键然后移动鼠标来开始橡皮筋选择是有意义的。我可以在不制作自己的 QRubberBand 的情况下做到这一点吗?如果没有,我该如何重新实现它?
我有一个QGraphicsView
和一个QGraphicsScene
,我启用了
this->setDragMode(QGraphicsView::RubberBandDrag);
用于橡皮筋选择。但是,在我的应用程序中,您需要按下 CTRL 键然后移动鼠标来开始橡皮筋选择是有意义的。我可以在不制作自己的 QRubberBand 的情况下做到这一点吗?如果没有,我该如何重新实现它?
如果你说 aQMainWindow
包含你的QGraphicsView
和场景,一种方法是重载QMainWindow的keyPressEvent
和方法,如下所示:keyReleaseEvent
void MyMainWindow::keyPressEvent( QKeyEvent * event )
{
if( event->key() == Qt::Key_Control ) {
graphicsView->setDragMode(QGraphicsView::RubberBandDrag);
}
QMainWindow::keyPressEvent(event);
}
void MyMainWindow::keyReleaseEvent( QKeyEvent * event )
{
if( event->key() == Qt::Key_Control ) {
graphicsView->setDragMode(QGraphicsView::NoDrag);
}
QMainWindow::keyReleaseEvent(event);
}
这会将选择模式设置RubberBandDrag
为只要按下 CTRL。再次松开该键时,拖动模式恢复为默认值NoDrag
,不再进行选择。在这两种情况下,事件也会转发到 QMainWindow 基类实现,这可能与您相关,也可能不相关。
埃里克的回答对我来说效果不佳。如果我在仍然拖动的同时释放键,则橡皮筋不会被清除并在屏幕上保持可见,直到下一次选择。
因为 QT 仅在释放鼠标时清除橡皮筋,所以我的解决方法是在仍处于橡皮筋模式时强制执行人工鼠标释放事件以正确清除它:
void MyQGraphisView::keyReleaseEvent( QKeyEvent * event )
{
if( event->key() == Qt::Key_Control ) {
if(QApplication::mouseButtons() & Qt::LeftButton)
mouseReleaseEvent(new QMouseEvent(QApplicationStateChangeEvent::MouseButtonRelease, mousePosOnScene, Qt::LeftButton, Qt::NoButton, Qt::NoModifier));
setDragMode(QGraphicsView::NoDrag);
}
QMainWindow::keyReleaseEvent(event);
}
更新:Qt 修复了这个错误(https://bugreports.qt.io/browse/QTBUG-65186)并将在 5.15 中部署