qtqt5qgraphicsviewqactionqstackedwidget

QStackedWidget connect QActions to custom QGraphicsView of QWidget


I've made a MainWindow with a QStackedWidget and a QMenuBar. One of my widgets contains a QGraphicsView that I promoted to my custom QGraphicsView (DrawingView). I'd like to connect the QActions from the menuBar to my custom DrawingView.

I managed to get the QActions that were connected to the widget working, but I don't know how to access the methods from the DrawingView.

This is the code I used for the other QActions:

draw  = qobject_cast<Drawing*>(ui->stackedWidget->widget(1));
connect(ui->actionOpen, &QAction::triggered, draw, &Drawing::openPhoto);
connect(ui->actionSave, &QAction::triggered, draw, &Drawing::saveFile);
connect(ui->actionExit, &QAction::triggered, draw, &Drawing::close);

I tried this for the DrawingView, but I know that it just makes a new DrawingView instead of using the one from the Draw ui.

drawView = new DrawingView();
connect(ui->actionZoom_In, &QAction::triggered, drawView, &DrawingView::zoomIn);
connect(ui->actionZoom_Out, &QAction::triggered, drawView, &DrawingView::zoomOut);

I also tried this, which gave an error on ui->stackedWidget->widget(1)->graphicsView:

drawView = qobject_cast<DrawingView*>(ui->stackedWidget->widget(1)->graphicsView); //also tried (ui->stackedWidget->widget(1)->ui->graphicsView)
connect(ui->actionZoom_In, &QAction::triggered, drawView, &DrawingView::zoomIn);
connect(ui->actionZoom_Out, &QAction::triggered, drawView, &DrawingView::zoomOut);

Any help on how to connect from the MainWindow or how to access the ui of MainWindow inside 2nd widget.


Solution

  • Isn’t your problem simply that graphicsView is a private member of the containing widget?

    You could either make it a public member or add a wrapper function:

    auto draw  = qobject_cast<Drawing*>(ui->stackedWidget->widget(1));
    connect(ui->actionZoom_In, &QAction::triggered, draw, &Drawing::zomIn);
    

    and in the Drawing class:

    void Drawing::zoomIn() {
        ui->graphicsView.zoomIn();
    }
    

    A third option is to