Search code examples
c++qtqgraphicsviewqmainwindowqtwidgets

Qt: Can't set drag mode


I've been stuck on this for a little while now, I'm trying to set the drag mode of my QGraphicsView to ScrollHandDrag so that I can build a panning feature on my application.

However whenever I try to set the drag mode Qt always complains that DragMode is an undeclared identifier.

I'm also aiming to build a crop functionality (I assume I'd be using rubber band dragging for that?), I'm just wondering why I can't set the drag mode on the View

void MainWindow::on_btnCrop_clicked()
{
    cropping = true;
    QApplication::setOverrideCursor(Qt::CrossCursor);

    // Stuck with this...
    ui->imageView->setDragMode(ScrollHandDrag);
}

^ I have tried multiple other workarounds but I've not yet found any solution, any suggestions would be greatly appreciated.


Solution

  • This is not QGraphicsView specific an issue, but generic C++. Your problem is located at this line:

    ui->imageView->setDragMode(ScrollHandDrag);
    

    The problem is that you assume that you have visibility to the ScrollHandDrag value, whereas it appears inside the QGraphicsView scope. Therefore, since you are trying to access that value in your MainWindow, you will need add the scope explicitly as follows:

    ui->imageView->setDragMode(QGraphicsView::ScrollHandDrag);
    

    Note that how even the documentation specifies the scope for this constant:

    QGraphicsView::ScrollHandDrag 1 The cursor changes into a pointing hand, and dragging the mouse around will scroll the scrolbars. This mode works both in interactive and non-interactive mode.

    Here is my minimal building code:

    #include <QGraphicsView>
    
    int main()
    {
        QGraphicsView graphicsView;
        graphicsView.setDragMode(QGraphicsView::ScrollHandDrag);
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT += widgets
    SOURCES += main.cpp
    

    Build and Run

    qmake && make