Reputation: 29
I'm trying to create a QGraphicScene (with appropriate View) in the MainWindow. The Scene is defined in a seperate class (a child widget to the mainwindow).
The open action works well and I can open every picture, but they always open in a new window and not within in the MainWindow.
When I create a label (or so) in the child widget, it is displayed correctly within the Mainwindow. So the problem seems to be the QGraphicScene or QGraphicView.
MainWindow:
MainWindow::MainWindow()
{
QWidget *widget = new QWidget;
setCentralWidget(widget);
PictureArea = new picturearea(this);
QHBoxLayout *HLayout = new QHBoxLayout(this);
HLayout->addWidget(PictureArea,1);
widget->setLayout(HLayout);
createActions();
createMenus();
this->setMinimumSize(800,600);
this->resize(800,600);
}
...
void MainWindow::open()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"),
QDir::currentPath(), tr("Image Files (*.png *.jpg)"));
if (!fileName.isEmpty())
{
QImage image(fileName);
if (image.isNull())
{
QMessageBox::information(this, tr("Image Viewer"),
tr("Cannot load %1.").arg(fileName));
return;
}
//transfer to child widget, guess no mistakes so far
PictureArea->setPicture(image);
}
}
picturearea:
picturearea::picturearea(QWidget *parent) : QWidget(parent)
{
}
void picturearea::setPicture(QImage image)
{
QGraphicsScene* scene = new QGraphicsScene();
QGraphicsView* view = new QGraphicsView(scene);
QGraphicsPixmapItem* item =
new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->addItem(item);
view->show();
}
How can I create the scene within the MainWindow and not in a separate window? I'm using QT 4.7.4, Windows7 64bit.
Upvotes: 1
Views: 1082
Reputation: 12931
You are creating a new QGraphicsScene
and QGraphicsView
every time you set a picture. And you are not putting your view
inside any layout or setting a parent to it, so it's opening in a new window when you call view->show()
.
You should create a QGraphicsView
and a QGraphicsScene
inside your constructor.
//picturearea.h
...
public:
QGraphicsView *view;
QGraphicsScene *scene;
...
//pircurearea.cpp
picturearea::picturearea(QWidget *parent) : QWidget(parent)
{
this->setLayout(new QVBoxLayout);
view = new QGraphicsView(this);
this->layout()->addWidget(view);
scene = new QGraphicsScene;
view->setScene(scene);
}
void picturearea::setPicture(QImage image)
{
scene->clear();
scene->addPixmap(QPixmap::fromImage(image));
}
Upvotes: 1