Qgraphicsscene 在函数内部获取 scenePos() 的麻烦 [英] Qgraphicsscene troubles to get scenePos() inside a function

查看:46
本文介绍了Qgraphicsscene 在函数内部获取 scenePos() 的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将 qgraphicsscene 子类化并尝试将鼠标坐标放入正常"函数中.我只让它在鼠标参与"功能上工作.抱歉,我是业余程序员.

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.

例如这里的scenePos() 工作:

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!!!";}}

在这里它根本不起作用,但是 QCursor::pos() 给出了奇怪的"位置:

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?

谢谢!:-)

推荐答案

如果你想获得相对于光标场景的位置,你必须首先获得 QGraphicsView 在光标下方(一个 QGraphicsScene 可以是 QGraphicsView 的一部分),为此,我们必须迭代并验证它是否在视口内,然后使用 QGraphicsView 的 mapToScene 方法计算相对于场景的位置:

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);
    }
}

这篇关于Qgraphicsscene 在函数内部获取 scenePos() 的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆