Search code examples
qt4qgraphicsviewqgraphicsscene

Multiple QGraphicsView for a single QGraphicsScene


I have one QGraphicsScene to which I have added some instances of QGraphicsItem.

I need to display a particular section of my whole scene in individual views.

To do that, I want to create multiple instances of QGraphicsView each of which displays a particular section of my QGraphicsScene(not a similar portion).

How can it be done?

QGraphicsScene mcpGraphicsScene = new QGraphicsScene(this);

QGraphicsRectItem * mcpGraphicsRect = mcpGraphicsScene->addRect(5,5,200,200);

QGraphicsLineItem * mcpGraphicsLine = mcpGraphicsScene->addLine(500,500,300,300);


QGraphicsView * mcpGraphicsView1 = new QGraphicsView(this);
mcpGraphicsView1->setScene(mcpGraphicsScene);
mcpGraphicsView1->setGeometry(260,20,311,500);

QGraphicsView * mcpGraphicsView2 = new QGraphicsView(this);
mcpGraphicsView2->setScene(mcpGraphicsScene);
mcpGraphicsView2->setGeometry(260,520,311,1061);

Solution

  • You are using the wrong function, you are using setGeometry which is telling the View where it should be placed relative to its parent (which is the widget, not the scene). To define the area of the scene that the view is responsible for showing you need to call use setSceneRect

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QGraphicsScene>
    #include <QGraphicsView>
    #include <QLayout>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QHBoxLayout* myLayout = new QHBoxLayout(this);
        QGraphicsScene* mcpGraphicsScene = new QGraphicsScene(this);
    
        mcpGraphicsScene->addRect(5,5,200,200);
        mcpGraphicsScene->addLine(500,500,300,300);
    
        QGraphicsView * mcpGraphicsView1 = new QGraphicsView(mcpGraphicsScene, this);
        mcpGraphicsView1->setSceneRect(0,0,150,150);
    
        QGraphicsView * mcpGraphicsView2 = new QGraphicsView(mcpGraphicsScene, this);
        mcpGraphicsView2->setSceneRect(0,150,600,600);
    
        myLayout->addWidget(mcpGraphicsView1);
        myLayout->addWidget(mcpGraphicsView2);
        QWidget *window = new QWidget();
        window->setLayout(myLayout);
        setCentralWidget(window);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }