Unsolved Set QGraphicsTextItem exactly in a mousePressEvent.
-
Hello again friends!
I implemented a subclass of QGraphicsScene to show numbers in this when is receiving a mouse click event. Everything works correctly but i want to do that better.
This is my code:
void subQGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { if (mouseEvent->button() == Qt::LeftButton) { QPointF p = mouseEvent->scenePos(); QFont f; int posFil = width/numFil; int posCol = height/numCol; float tam; if (posFil <= posCol){ tam = posFil/4; }else{ tam = posCol/4; } f.setPointSizeF(tam); QString s = QString::number(count); QGraphicsTextItem * text = addText(s,f); float point; for (int i=1;i<numFil;i++){ //Si se encuentra entre la linea dibujada y la anterior. if ( (p.x() < (posFil*i)) && ((posFil*(i-1)) < p.x())){ point = ((posFil*i + posFil*(i-1))/2); p.setX(point); } // Si tratamos con la última línea if ( i == numFil-1){ if ( (p.x() > posFil*i) && ((posFil*(i+1)) > p.x())){ point = ((posFil*i + posFil*(i+1))/2); p.setX(point); } } } for (int j=1;j<numCol;j++){ //Si se encuentra entre la linea dibujada y la anterior. if ( (p.y() < (posCol*j)) && ((posCol*(j-1)) < p.y())){ point = ((posCol*j + posCol*(j-1))/2); p.setY(point); } if ( j == numCol-1){ if ( (p.y() > posCol*j) && ((posCol*(j+1)) > p.y())){ point = ((posCol*j + posCol*(j+1))/2); p.setY(point); } } } text->setPos(p.x(),p.y()); count++; } }
how you can see, i set the Item with setPos of that, but the problem is that setPos indicate where start the item. Then, when i use mouse event, the item starts in that position and the item appears a little bit more down that this click. I want that this coordinates of the mouse event would be the middle of the item. How can i do that? Thanks!