0

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.

m7913d
  • 10,244
  • 7
  • 28
  • 56
  • Please consider posting the exact error message. Also a [mcve] would be really helpful to assist you further. What is the relation between `Drawing` and `DrawingView`? – m7913d Nov 22 '19 at 16:13
  • It may be easier to setup your ui (partially) from C++. It give you better control over how to access your specific classes. – m7913d Nov 22 '19 at 16:15
  • Or you can try to manage the connects in Qt Designer itself. – m7913d Nov 22 '19 at 16:15

1 Answers1

1

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

  • emit a custom zoomIn signal from the MainWindow
  • make the main window accessible to Drawing (e.g. passing it to the constructor or creating a global mainWindow singleton)
  • and do the connect directly in Drawing
x squared
  • 3,173
  • 1
  • 26
  • 41