Qt:限制QGraphicsItem在另一个QGraphicsItem中的可移动区域
Qt: restrict movable area of a QGraphicsItem inside an other QGraphicsItem C++
我认为我的问题类似于这篇文章,但在c++和QGraphicsItem内。
我想在另一个QGraphicsItem中修复我的对象的可移动区域。如果我想把对象移到外面,我想让它留在里面。
也许我们的想法是使用setParentItem()
。
有人知道如何限制一个QGraphicsItem内的可移动区域吗?
是的,你是正确的。在这里,你必须重新实现itemChange。从qt文档
QVariant Component::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene()) {
// value is the new position.
QPointF newPos = value.toPointF();
QRectF rect = scene()->sceneRect();
if (!rect.contains(newPos)) {
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
,其中scene()指项目所在的QGraphicsScene。如果你不使用QGraphicScene,你必须设置一个适当的QRectF(可能从父项目几何)。
我的问题解决了!
为此,我添加了重新定义如何设置QGraphicsItem
的位置。我的条目是由boundingRect()
定义的,像这样:
QRectF MyClass::boundingRect() const
{
return QRectF( -_w/2, -_h/2, _w, _h);
}
所以我想让这个QRectF
留在场景中。我的项目的位置是由QRectF
的中心定义的。使用@Salvatore Avanzo提出的Qt文档中的代码,这是我的代码:
QVariant Aabb::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene()) {
// value is the new position.
QPointF newPos = value.toPointF();
QRectF rect = scene()->sceneRect();
if (!rect.contains(newPos.x() - _w/2, newPos.y() - _h/2)||!rect.contains(newPos.x() - _w/2, newPos.y() + _h/2)||!rect.contains(newPos.x() + _w/2, newPos.y() + _h/2)||!rect.contains(newPos.x() + _w/2, newPos.y() - _h/2))
{
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right() - _w/2, qMax(newPos.x() , rect.left() + _w/2)));
newPos.setY(qMin(rect.bottom() - _h/2, qMax(newPos.y() , rect.top() + _h/2)));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
不要忘记设置场景的QRectF
(参见问题中的评论)
相关文章:
- 内置函数可查看CPP中的成员变量
- 可组合的lambda/std::函数与std::可选
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用gcc从静态链接的文件中查找可选符号
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 对于结构,表达式必须是可修改的ivalue
- 使外部项目可用于find_package CMake
- 将寄存器设计成可由C和C++访问的外设的最佳实践
- C++Union/Struct位域的实现和可移植性
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 将QGraphicsItem的移动区域限制在多边形区域内
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 我需要分发哪些版本的可再分发文件
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 如何在对<char>C++程序进行逆向工程的同时将 std::basic_string 转换为 Rust 可读值?
- 在Qt中实现无限可缩放的画布
- 是否可以为 QPixmap 派生类嵌入缩放方法?
- Qt:限制QGraphicsItem在另一个QGraphicsItem中的可移动区域