Reputation: 55
I'm trying to build a custom widget with a QGraphicsScene inside it.
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();
}
But when I run the widget, only an empty scene shows up in the QGraphicsView widget inside the main widget.
Upvotes: 0
Views: 671
Reputation: 73304
Try it like this instead; I think one problem is that scene->width()
and scene->height()
are very likely both returning 0, at least on your first call to them, since sceneRect()
defaults to returning a QRect big enough to fit the current contents of the scene (which is initially empty):
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);
}
Upvotes: 1