qt橡皮筋选择与特定的键盘键

问题描述 投票:2回答:2

我有一个QGraphicsViewQGraphicsScene我启用了

this->setDragMode(QGraphicsView::RubberBandDrag);

用于橡皮筋选择。但是,在我的应用程序中,您需要按下CTRL键,然后移动鼠标以启动橡皮带选择。我可以在不制作自己的QRubberBand的情况下完成这项工作吗?如果没有,我该如何重新实现呢?

c++ qt qgraphicsview qgraphicsscene rubber-band
2个回答
2
投票

如果你说QMainWindow包含你的QGraphicsView和Scene,一种方法是重载QMainWindow的keyPressEventkeyReleaseEvent方法,如下所示:

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);

}

只要按下CTRL,这将把选择模式设置为RubberBandDrag。当再次释放键时,拖动模式将设置回默认的NoDrag,并且不会执行任何选择。在这两种情况下,事件也会转发到QMainWindow基类实现,这可能与您相关,也可能不相关。


0
投票

Erik的回答对我来说效果不佳。如果我在拖动时释放按键,则橡皮筋不会被清除并在屏幕上保持可见状态,直到下一次选择。

由于QT仅在鼠标释放时清除橡皮筋,我的解决方法是在仍然处于Rubberband模式时强制进行人工鼠标释放事件以使其正确清除:

void MyQGraphisView::keyReleaseEvent( QKeyEvent * event )
{
    if( event->key() == Qt::Key_Control ) {
        mouseReleaseEvent(new QMouseEvent(QApplicationStateChangeEvent::MouseButtonRelease, mousePosOnScene, Qt::LeftButton, Qt::NoButton, Qt::NoModifier));   
        setDragMode(QGraphicsView::NoDrag);
    }
    MyQGraphisView::keyReleaseEvent(event);

}
© www.soinside.com 2019 - 2024. All rights reserved.