[英]Why does my QGraphicsView not showing up in my MainWindow in Qt4?
這可能是非常明顯的事情,但我有一個新的Qt,無法弄明白。 我有一個簡單的MainWindow,它有一個按鈕。 單擊該按鈕時,我想創建一個QGraphicsScene,添加幾行,然后在Window中顯示。 但是,當我在Window中運行此代碼時,它不會顯示。
但是,如果我將其作為QApplication運行,它會顯示正常。 我錯過了什么?
這是MainWindow中的代碼:
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();
}
你的QGraphicsView需要一個主窗口的中央控件(或者你想把它置於其上的任何小部件)來設置為父窗口。 此外,您需要“新”視圖和場景對象以將它們放在堆上,這樣一旦drawScene完成它們就不會被銷毀。 看到以下對您的代碼的更改將適合您:
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();
希望這有幫助,問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.