QGraphicsItems 没有显示 QGraphicsScene

QGraphicsItems not showing up QGraphicsScene

我正在尝试构建一个带有 QGraphicsScene 的自定义小部件。

class Graphics:public QWidget{
  public:
 Graphis();
}

Graphics::Graphics(){
 QGraphicsScene* scene = new QGraphicsScene(this);
    
    
    QGridLayout* grid = new QGridLayout;

    
    
    QGraphicsView* view = new QGraphicsView(this);
    
    
    QGraphicsLineItem* y = new QGraphicsLineItem(scene->width()/2, 0, scene->width() / 2, scene->height());
    QGraphicsLineItem* x = new QGraphicsLineItem(0, scene->height() / 2, scene->width(), scene->height() / 2);
    scene->addItem(y);
    scene->addItem(x);
    
    

    grid->addWidget(view, 0, 0, 1, 1);
    setLayout(grid);

    view->setScene(scene);
    view->show();
}

但是当我 运行 小部件时,只有一个空场景出现在主小部件内的 QGraphicsView 小部件中。

换成这样试试;我认为一个问题是 scene->width()scene->height() 很可能都返回 0,至少在你第一次调用它们时是这样,因为 sceneRect() 默认返回一个足够大的 QRect 以适应当前场景内容(最初为空):

Graphics::Graphics(){
    QGraphicsScene* scene = new QGraphicsScene(this);
    QGridLayout* grid = new QGridLayout(this);
    QGraphicsView* view = new QGraphicsView(scene, this);

    scene->setSceneRect(0, 0, 200, 200);
    QGraphicsLineItem* y = new QGraphicsLineItem(scene->width()/2, 0, scene->width() / 2, scene->height());
    QGraphicsLineItem* x = new QGraphicsLineItem(0, scene->height() / 2, scene->width(), scene->height() / 2);
    scene->addItem(y);
    scene->addItem(x);

    grid->addWidget(view, 0, 0, 1, 1);
}