c++ - 使用 mouseMoveEvent 限制 QGraphicsItem 的移动

标签 c++ qt c++11 qgraphicsscene qgraphicsitem

我正在尝试适本地限制 QGraphicsItem(特别是 QGraphicsRectItem)的移动,而不更改 native 行为以用作 X 轴上的滚动条。

我尝试覆盖 mouseMoveEvent 函数,但随后我需要重写矩形在 X 和 Y 方向上的行为。充其量,我可以使用鼠标将矩形捕捉到一个位置。 (此处矩形将捕捉,因此鼠标将其保持在中点):

void SegmentItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
  setY(0);
  setX(event->scenePos().x() - boundingRect().width()/2);
}

我正在查看 itemChange,如 here 所述,但它看起来有点笨重而且不够优雅。 编辑:这应该可以工作,但我目前无法强制它工作。

有没有办法只限制 y 轴的移动? (我还需要为滚动条创建止点,但稍后。)

最佳答案

我修改了 itemChange 类引用页面中的代码,并对其进行了增强,使我的 QGraphicsRectItem 的所有四个角都位于 QGraphicsScene:

QVariant SegmentItem::itemChange(GraphicsItemChange change, const QVariant &value)
 {
     if (change == ItemPositionChange && scene()) {
         // value is the new position.
         QPointF newPos = value.toPointF();
         QRectF rect = scene()->sceneRect();
         rect.setWidth(rect.width() - boundingRect().width());
         rect.setHeight(0);
         if (!rect.contains(newPos)) {
             // Keep the item inside the scene rect.
             newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
             newPos.setY(2);
             return newPos;
         }
     }
     return QGraphicsItem::itemChange(change, value);
 }

关于c++ - 使用 mouseMoveEvent 限制 QGraphicsItem 的移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221482/

相关文章:

C++如何将 vector 与模板一起使用?

c++ - cpp 核心指南中的 owner<T*> p 语法

c++ - 为什么将 `istream&` 取到临时 `stringstream` 工作,但取 `stringstream&` 时不起作用?

c++ - Qt - 如何将多个 QGroupBox 添加到 QTabWidget?

c++ - 制作标签数组的有效方法

qt - 在 X 上拖动对象下方缓慢重绘... Qt 能否强制拖放操作仅限内部操作?

C++ 入门第 5 版。 : using sort on a vector of pointers is it undefined?

c++ - 辅助函数 : static in cpp or define as static helper class method

c++ - double vector 到 vector 字节

c++ - 使用智能指针的访问冲突