1

这可能是非常明显的事情,但我对 Qt 有一个新的认识,无法弄清楚。我有一个简单的 MainWindow,它有一个按钮。单击该按钮时,我想创建一个 QGraphicsScene,添加几行,然后在窗口中显示。但是,当我在窗口中运行此代码时,它不会显示出来。

但是,如果我将它作为 QApplication 运行,它会显示得很好。我错过了什么?

这是主窗口中的代码:

void TheDrawings::drawScene() {
 qDebug() << "Setting up Scene";

 QGraphicsScene scene(QRect(-50, -50, 400, 200));

 QPen pen(Qt::red, 3, Qt::DashDotDotLine);

 QGraphicsRectItem *rectItem = new QGraphicsRectItem(QRect(-50, -50, 400,
   200), 0, &scene);
 rectItem->setPen(pen);
 rectItem->setBrush(Qt::gray);

 QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(
   "Amit Bahree", 0, &scene);
 textItem->setPos(50, 0);

 QGraphicsEllipseItem *eclipseItem = new QGraphicsEllipseItem(QRect(170, 20,
   100, 75), 0, &scene);
 eclipseItem->setPen(QPen(Qt::darkBlue));
 eclipseItem->setBrush(Qt::darkBlue);

 QGraphicsPolygonItem *polygonItem = new QGraphicsPolygonItem(QPolygonF(
   QVector<QPointF> () << QPointF(10, 10) << QPointF(0, 90)
     << QPointF(40, 70) << QPointF(80, 110) << QPointF(70, 20)),
   0, &scene);
 polygonItem->setPen(QPen(Qt::darkGreen));
 polygonItem->setBrush(Qt::yellow);

 qDebug() << "Setting up the view";
 QGraphicsView view;
 view.setScene(&scene);
 view.show();

}

4

1 回答 1

4

your QGraphicsView needs a centralwidget of the mainwindow (or whatever widget you want to put it on top of) to be set as a parent. Also you need to "new" your view and scene objects to put them on the heap so they don't get destroyed once drawScene finishes. See of following changes to your code would work fine for you:

QGraphicsScene* scene = new QGraphicsScene(QRect(-50, -50, 400, 200));
...
QGraphicsView* view = new QGraphicsView(ui->centralWidget);
view->setScene(scene);
view->setGeometry(QRect(50, 50, 400, 200));
view->show();

hope this helps, regards

于 2010-01-03T05:50:30.100 回答