sh ze
sh ze

Reputation: 169

Error while using QGraphicsScene functions in Qt

I'm getting errors when I run a qt project and I can't understand what is the reason

errors:

'class MainWindow' has no member named 'setSceneRect' 'class MainWindow' has no member named 'setScene' `mapToScene' was not declared in this scope

the code:

mainwindow.cpp:

 MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
QGridLayout * gridLayout = new QGridLayout(ui->centralWidget);
gridLayout->addWidget( new MainWindow() );

scene = new QGraphicsScene();
    this->setSceneRect(50, 50, 350, 350);
    this->setScene(scene);
 }

 void MainWindow::mousePressEvent(QMouseEvent * e)
{
    double rad = 1;
    QPointF pt = mapToScene(e->pos());
    scene->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0,
        QPen(), QBrush(Qt::SolidPattern));
}

mainwindow.h:

private:
Ui::MainWindow *ui;
QGraphicsScene * scene;

Upvotes: 0

Views: 2030

Answers (1)

Nejat
Nejat

Reputation: 32665

First of all do not make an instance of MainWindow in it's constructor. I think instead of gridLayout->addWidget( new MainWindow() ); you should add your view to the main window :

gridLayout->addWidget(view);

You should call setSceneRect on QGraphicsScene :

scene->setSceneRect(50, 50, 350, 350);

Also you should assign a scene to a QGraphicsView by calling QGraphicsView::setScene :

QGraphicsView * view = new QGraphicsView(this) ;
view->setScene(scene);

mapToScene is a function of QGraphicsView. So you should have something like :

QPointF pt = view->mapToScene(e->pos());

Finally i should mention that you can have a custom class which inherits from QGraphicsView and implement mousePressEvent and other things related to scene and drawing there. Then you can have an instance of your custom class in your MainWindow.

Upvotes: 1

Related Questions