【问题标题】:How to appropriately get position of QGraphicsRectItem after drag-release?拖动释放后如何正确获取 QGraphicsRectItem 的位置?
【发布时间】:2016-12-15 03:17:15
【问题描述】:

我想有一个在线监控系统,可以知道形状当前的位置,但是我得到了非常奇怪的项目坐标,而且每次我创建新的并拖动它时,它的尺寸都会增加 1。

初始位置(地图大小为 751 x 751,通过输出到qDebug() 进行检查,场景绑定到黄色空间):

将它拖到左上角。

正如您在开始时看到的那样,它在 (200;200) 上,但在拖动后它在 (-201;-196) 上。删除它并在相同位置创建具有相同属性的新形状后,由于它在地图之外,因此看不到新形状,这表明编辑未显示正确的数据。

这里是更新编辑的代码:

void CallableGraphicsRectItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
    QGraphicsRectItem::mouseReleaseEvent(event);
    ptr->updateEdits(this);
}

这是我设法缩减为updateEdits()的内容:

void MainWindow::updateEdits(QAbstractGraphicsShapeItem* item)
{
    //stuff not related to scene

    auto posReal = item->scenePos();
    auto pos = posReal.toPoint();

    //create QString from coordinates
    QString coordinate;
    coordinate.setNum(pos.x());
    ui->leftXEdit->setText(coordinate);
    coordinate.setNum(pos.y());
    ui->upperYEdit->setText(coordinate);

    //get width and height for rect, radius for circle    
    auto boundingRectReal = item->sceneBoundingRect();
    auto boundingRect = boundingRectReal.toRect();
    ui->widthEdit->setText(QString::number(boundingRect.width()));
    //disables height edit for circles, not really relevant
    if (!items[currentShapeIndex].isRect)
    {
        ui->heightEdit->setDisabled(true);
    }
    else
    {
        ui->heightEdit->setDisabled(false);
        ui->heightEdit->setText(QString::number(boundingRect.height()));
    }
}

这是我如何将QGraphicsScene 锚定到黄色区域的左上角:

scene->setSceneRect(0, 0, mapSize.width() - 20, mapSize.height() - 20);
ui->graphicsView->setScene(scene);

如何向编辑报告正确的数据?

【问题讨论】:

    标签: c++ qt qgraphicsitem


    【解决方案1】:

    您最好重写 itemChange 方法并使用 ItemPositionHasChanged 通知。您必须在项目上设置 ItemSendsGeometryChanges 标志,以便它接收这些通知。

    当您仍在 mouseReleaseEvent 方法中时,我不确定您的项目的最终位置是否已设置。在 itemChange 中跟踪它会确保数据是有效的,而这种东西就是它的用途。

    另外,请注意“pos”在项目的父坐标中,“boundingRect”在项目的坐标空间中。如果你想确定你使用的是场景坐标,你应该使用“scenePos”和“sceneBoundingRect”。如果项目没有父项,则“pos”和“scenePos”将返回相同的值,但“boundingRect”和“sceneBoundingRect”通常会有所不同。

    【讨论】:

    • 我还应该注意,“boundingRect”和“sceneBoundingRect”的左上角值会有所不同,但通常不会在宽度和高度上有所不同,除非项目应用了变换矩阵。
    • 我找到了一个名为 ItemSendsScenePositionChanges 的标志。好点了吗?
    • 这不是更好;这不一样。检查两个标志上的文档,看看哪一个更适合您的情况。
    • 我尝试过覆盖itemChange() 方法,但结果还是一样。可能我应该发布其他代码吗?
    • 我尝试减少它并添加有用的 cmets。更新了帖子。
    猜你喜欢
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2013-04-28
    • 2017-09-16
    • 1970-01-01
    相关资源
    最近更新 更多