【问题标题】:Point 0/0 of QGraphicsItem.scene() (restricting item movement)QGraphicsItem.scene() 的 0/0 点(限制项目移动)
【发布时间】:2012-06-20 22:04:06
【问题描述】:

我在限制 QGraphicItems 的移动时遇到问题:

QVariant CustomRectItem::itemChange(GraphicsItemChange change, const QVariant& value)
{
    if (change == QGraphicsItem::ItemPositionChange && this->scene()) {

        // parameter value is the new position
        QPointF newPos = value.toPointF();
        QRectF rect = this->scene()->sceneRect();

        // keep the item inside the scene rect
        if (!rect.contains(newPos)) {
            if(newPos.x() < rect.x())
                newPos.setX(rect.x());
            return newPos;
        }
    }
    return QGraphicsItem::itemChange(change, value);
}

这段代码应该防止一个项目被拖到场景的左边 从而增加它的大小。它有点工作。 我的问题是:

我在创建场景时插入项目。 On 位于 x=0(场景坐标),另一个位于 x=10(场景坐标) 使用此代码,我不能拖动 x=10 左侧的第二个项目。

似乎对 QGraphicsItem::scene() 的调用为这两个项目返回了不同的场景。

【问题讨论】:

    标签: qt qgraphicsitem qgraphicsscene


    【解决方案1】:

    我在这个帖子中找到了答案: Why does QGraphicsItem::scenePos() keep returning (0,0)

    问题出在项目的创建中。 小心不要将它们放置在构造函数中。出现在场景中后必须定位它们...

    for (int i = 0; i < 3; ++i){
        for (int j = 0; j < 3; ++j){
            item = new CustomRectItem(0, 0, 20, 20);
            item->setFlags(QGraphicsItem::ItemIsMovable |
                           QGraphicsItem::ItemSendsScenePositionChanges);
            scene->addItem(item);
            item->setPos(i*30, j*30);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-25
      • 2018-10-03
      • 2016-08-24
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多