如何在拖放后适当获取QGraphicsRectItem的位置?

时间:2016-12-13 21:17:18

标签: c++ qt qgraphicsitem

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

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

Initial position

将其拖动到左上角。

enter image description here

正如你在开始时所看到的那样(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);

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

1 个答案:

答案 0 :(得分:1)

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

当你还在mouseReleaseEvent方法中时,我不确定你的项目的最终位置是否已设置。在itemChange中跟踪它将确保数据有效,这就是它的用途。

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

相关问题