我无法让QGraphicsView出现在QVBoxLayout对象中,我也不知道哪里出了问题。我的代码可以编译,因此不会引发任何错误。这是我的简单代码。 (我是Qt和C++ newb)。在底部,我将QPushButton小部件添加到布局中,并且显示得很好。谢谢您的帮助!

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"));

最佳答案

没有足够的背景信息,所以我无法确切知道发生了什么。但是,如果它们在函数中,那么您将声明函数退出后就消失的局部变量。如果您是主程序,您的代码应该看起来像这样,但它可能会崩溃:

 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();

我建议动态分配对象:
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();
}

不要忘记删除父对象,这样它就不会泄漏内存。

09-07 10:49