Pergunta

I opened each Image in a new tab on QGraphicsScene and QGraphicsView by this

    void MainWindow::on_actionOpen_triggered()
    {
        QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::currentPath());
        if (!fileName.isEmpty()) {
           QImage image(fileName);
            if (image.isNull()) {
               QMessageBox::information(this, tr("Master Measure"),
                                tr("Cannot load %1.").arg(fileName));
               return;
            }

            scene = new QGraphicsScene;
            view = new QGraphicsView;

           view->setScene(scene);
           tabWidget->addTab(view,"someTab");

           scene->addPixmap(QPixmap::fromImage(image));
           scene->setBackgroundBrush(QBrush(Qt::lightGray, Qt::SolidPattern));

           QFileInfo fileInfo = fileName;
           tabWidget->setTabText(ui->tabWidget->count()-1, fileInfo.baseName());
           tabWidget->setCurrentIndex(ui->tabWidget->count()-1);
        }
    }

I want to draw something on each image by clicking.

so I did this by click press event

void MainWindow::mousePressEvent(QMouseEvent *event)
{
     QPen pen(Qt::black);
     QBrush brush(Qt::red);
     pen.setWidth(6);
     scene->addEllipse(0,0,1000,500,pen,brush);
}

it just draw Ellipse on last opened image (tab).

I don't know how to solve this problem.

I appreciate any idea. Thank you.

Foi útil?

Solução

Obviously scene variable points to the last created scene. When you create new scene, old pointer is lost because you don't save it anywhere. So you need to preserve all scene and view pointers somewhere and use the currently visible objects.

I advise you to create a QGraphicsView's subclass (let's call it MyView) that will be responsible to every tab's contents. Pass the filename to the constructor of this object. In the constructor create a scene and store it in a member variable. Reimplement MyView::mousePressEvent to perform drawing.

Then you can add new tabs like this:

MyView* view = new MyView(filename);
view ->addTab(view,"someTab");

When the user clicks a view, MyView::mousePressEvent method or the respective MyView object will be invoked. Each view will see only its own scene variable, and the respective scene will be edited.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top