Animal Rights
Animal Rights

Reputation: 9397

Qt Framework: How to display a QGraphicsView in a layout?

I am having trouble getting a QGraphicsView to show up in a QVBoxLayout object and I have no idea what is wrong. My code compiles so no errors are being thrown. Here is my simple code. (I am a Qt and C++ newb). At the bottom, I add a QPushButton widget to the layout and that shows up fine. Thanks for your help in advance!

QGraphicsScene scene;
QGraphicsView view(&scene);
view.setBackgroundBrush(QImage(":/images/bg/tile.png"));
view.setCacheMode(QGraphicsView::CacheBackground);
QPixmap pixmap("images/icons/dsp.gif");
QGraphicsPixmapItem* dsp = scene.addPixmap(pixmap);
view.show();
vlayout->addWidget(&view);
vlayout->addWidget(new QPushButton("some button here"));

Upvotes: 3

Views: 10011

Answers (1)

Arlen
Arlen

Reputation: 6845

Not enough context, so I can't tell what's happening exactly. But, if those are in a function, then you are declaring local variables that are gone once the function exits. If you are in the main, you're code should look something like this, but it will probably crash:

 QApplication app(argc, argv);
  QGraphicsScene scene;
  QGraphicsView view(&scene);

  QWidget widget;
  view.setBackgroundBrush(Qt::red);
  QVBoxLayout vlayout;
  widget.setLayout(&vlayout);
  vlayout.addWidget(&view);
  vlayout.addWidget(new QPushButton("some button here"));
  widget.show();

I recommend dynamically allocating objects:

int main(int argc, char* argv[]){

  QApplication app(argc, argv);
  QGraphicsScene* scene = new QGraphicsScene;
  QGraphicsView* view = new QGraphicsView(scene);

  QWidget *widget = new QWidget;
  view->setBackgroundBrush(Qt::red);
  QVBoxLayout* vlayout = new QVBoxLayout(widget);

  vlayout->addWidget(view);
  vlayout->addWidget(new QPushButton("some button here"));
  widget->show();
  return app.exec();
}

Don't forget to delete the parent object so it doesn't leak memory.

Upvotes: 3

Related Questions