Reputation: 197
I've been trying to use the graphic view framework to draw nodes where I click. However, I can't get the position right.
This behaviour happens : I click on the yellow point and the node appears there
So here's the code for mainwindow.cpp :
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
scene = new GraphScene(this);
ui->setupUi(this);
ui->graphicsView->setScene(scene);
ui->graphicsView->setSceneRect(ui->graphicsView->rect());
ui->graphicsView->setFrameStyle(0);
ui->graphicsView->show();
}
the custom scene mousePressEvent:
void GraphScene::mousePressEvent(QGraphicsSceneMouseEvent *event){
if (!this->itemAt(event->scenePos(), QTransform())){
this->addItem(new NodeItem(event->scenePos()));
this->update();
}
}
And the node item :
NodeItem::NodeItem(QPointF position) {
this->setPos(position) ;
}
void NodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
painter->drawEllipse(pos(), 30.0, 30.0);
}
QRectF NodeItem::boundingRect() const{
return QRectF(pos(), QSizeF(30,30));
}
I tried my best to fix it but I've stuck for a while and can't fix it. I'll appreciate any help.
Upvotes: 1
Views: 268
Reputation: 243955
QGraphicsView
and QGraphicsScene
handle different coordinate systems, in the case of boundingRect()
and paint()
methods they must do in local coordinates with respect to the item and you should not use the pos()
method since that refers to coordinates with respect to the scene.
void NodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/){
painter->drawEllipse(boundingRect());
}
QRectF NodeItem::boundingRect() const{
return QRectF(QPointF(-15, -15), QSizeF(30,30));
}
Upvotes: 1