Qgraphicsscene troubles to get scenePos() inside a

2019-08-14 16:47发布

问题:

I have subclassed a qgraphicsscene and trying to get the mouse coords inside a "normal" function. I only get it working on "mouse involved" function. Sorry I'm amateur programmer.

For exmample here scenePos() works:

void mousePressEvent(QGraphicsSceneMouseEvent *event)
  {
// qDebug() << "Custom scene clicked.";
   if(event->modifiers() == Qt::ControlModifier) {
        if(event->button() == Qt::LeftButton) {
            QPointF pos = {event->scenePos().x(), 70};
            addChordnueve(pos); // crea 1 item at mouse x e y = 70
//        } if(event->modifiers() == Qt::ControlModifier & event->modifiers() == Qt::ShiftModifier) {
   qDebug() << "Control!!!";}}

Here it doesn't works at all, but got QCursor::pos() giving "weird" positions:

void preaddExtChord()
{
    auto *hellos = scenePos(); //<- It doesn't works

    int xplace = QCursor::pos().x()-620;
    int yplace = QCursor::pos().y()-380;

    QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem("n");
    item->setFont(QFont ("omheads", 20));
    item->setPos(xplace, yplace);
    addItem(item);
}

I searched a lot during months but couldn't find a solution,... maybe I'm doing a wrong approach, or either there is some easier possibilitie to get the mouse coords inside this type of functions?

Thanks! :-)

回答1:

If you want to obtain the position with respect to the cursor scene you must first obtain that QGraphicsView is below the cursor (a QGraphicsScene can be part of QGraphicsView), for this we must iterate and verify if it is inside the viewport, then calculate the position with respect to the scene using the mapToScene method of QGraphicsView:

QPoint p = QCursor::pos();
for(QGraphicsView *view: views()){
    QWidget *viewport = view->viewport();
    QRect vr = viewport->rect();
    QPoint vp = viewport->mapFromGlobal(p);
    if(vr.contains(vp)){
        QPointF sp = view->mapToScene(vp);
        QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem("n");
        item->setFont(QFont("omheads", 20));
        item->setPos(sp);
        addItem(item);
    }
}