QT 图形场景/视图 - 用鼠标移动

Ark*_*ker 1 c++ qt qgraphicsview qgraphicsscene

我创建了自己的类(视图和场景)来显示我添加到其中的图像和对象,甚至在我的视图中实现了放大/缩小功能,但现在我必须添加新功能,我什至不知道如何开始寻找它。

  • 每当我按下鼠标的滚动按钮并按住它时 - 我希望在场景中移动,以查看它的不同部分 - 就像我使用滑块一样。它应该类似于任何其他程序,允许放大/缩小图像并在放大的图片中移动以查看它的不同部分。

不幸的是 - 我什至不知道如何寻找一些基本的东西,因为“移动”和类似的东西是指拖动对象。

编辑 1

void CustomGraphicView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::MidButton)
    {
        setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        translate(event->x(),event->y());
    }
}
Run Code Online (Sandbox Code Playgroud)

试过这个 - 但它正在反向工作。

Tom*_*mas 5

我想你知道如何使用 Qt 处理事件。

因此,要翻译(移动)您的视图,请使用该QGraphicsView::translate()方法。

编辑

如何使用它:

void CustomGraphicsView::mousePressEvent(QMouseEvent* event)
{
    if (e->button() == Qt::MiddleButton)
    {
        // Store original position.
        m_originX = event->x();
        m_originY = event->y();
    }
}

void CustomGraphicsView::mouseMoveEvent(QMouseEvent* event)
{
    if (e->buttons() & Qt::MidButton)
    {
        QPointF oldp = mapToScene(m_originX, m_originY);
        QPointF newP = mapToScene(event->pos());
        QPointF translation = newp - oldp;

        translate(translation.x(), translation.y());

        m_originX = event->x();
        m_originY = event->y();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,还需要“setTransformationAnchor(QGraphicsView::NoAnchor)”才能使事情正常进行。 (2认同)