Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: QGraphicsScene mouse position always (0,0)

Tags:

c++

qt

I've created my own class that inherits from QGraphicsScene. I've also make two methods for mouse events. Later I do qDebug() to check if position of my click is correct, and it looks that it's not correct. It always returns me QPoint(0,0).

I've tried many mapfrom - things, but nothing worked. Is there way to make those positions work correctly?

Some code: MyScene.cpp

#include "pianoscene.h"
#include <QDebug>
#include <QGraphicsView>

MyScene::MyScene()
{
    /*setRect(0,0,100,100);
    QGraphicsRectItem *kek = new QGraphicsRectItem;
    QPen pen;
    pen.setColor(Qt::red);
    kek->setRect(0,0,50,50);
    kek->setPen(pen);
    this->addItem(kek);*/
}

void MyScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QPoint punkt = views().first()->mapFromScene(event->pos().toPoint());
    qDebug()<<"wcisk"<<punkt;
}

void MyScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug()<<"wcisk"<<event->pos();
}
like image 630
Lizard_Paszczyk Avatar asked Jan 29 '23 03:01

Lizard_Paszczyk


1 Answers

pos() contains the item coordinates, not the scene coordinates. To get scene coordinates, use scenePos():

void MyScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QPoint punkt = views().first()->mapFromScene(event->scenePos().toPoint());
    qDebug()<<"wcisk"<<punkt;
}

void MyScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug()<<"wcisk"<<event->scenePos();
}

Also, if you just need to propagate coordinates to other functions, don't use toPoint(). If you have no actual reason to convert to a QPoint, just use QPointF, as returned by scenePos() and pos(). No need for needless conversions.

like image 157
Nikos C. Avatar answered Feb 03 '23 17:02

Nikos C.