如何为 QGraphicsPixmapItem 设置鼠标碰撞框?[QT/C++]
How to Set Mouse Collision Box for QGraphicsPixmapItem? [QT/C++]
当在QGraphicsPixmapItem中重新实现任何鼠标事件函数(如mousePressEvent
,mouseReleaseEvent
,mouseMoveEvent
时,图形项使用像素完美碰撞。例如,对于要触发的mousePressEvent
,单击时鼠标必须正好位于像素图中可见像素的顶部。
另一方面,我希望碰撞是基于像素图的宽度和高度的广义框:[0, 0, width, height]
。
如何做到这一点?
(一些示例代码导致人们似乎喜欢这样(:
class MyGraphicsItem: public QGraphicsPixmapItem {
public:
MyGraphicsItem(): QGraphicsPixmapItem() {}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) {
// do stuff. Will be called when clicked exactly on the image
QGraphicsPixmapItem::mousePressEvent(event);
}
}
感谢 SteakOverflow 在正确的方向上提供了一个点。
艾伊莱特,这是你必须做的:
class MyGraphicsItem: public QGraphicsPixmapItem {
public:
MyGraphicsItem(): QGraphicsPixmapItem() {
// Change shape mode in constructor
setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) {
// do stuff. Will be called when clicked exactly on the image
QGraphicsPixmapItem::mousePressEvent(event);
}
}
或者,您可以执行以下操作:
class MyGraphicsItem: public QGraphicsPixmapItem {
public:
MyGraphicsItem(): QGraphicsPixmapItem() {}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) {
// do stuff. Will be called when clicked exactly on the image
QGraphicsPixmapItem::mousePressEvent(event);
}
// ::shape defines collision.
// This will make it a rect based on general dimensions of the pixmap
QPainterPath shape() const {
if(!pixmap().isNull()) {
QPainterPath path;
path.addRect(0, 0, pixmap().width(), pixmap().height());
return path;
} else {
return QGraphicsPixmapItem::shape();
}
}
}
相关文章:
- Qt VTK交互风格的信号到小部件
- QT在错误的班级中寻找空位
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 如何在Qt窗口小部件中使用QStringView(或QStringRef)
- 如何在Qt C++中更改光标
- 如何在MS Visual Studio 2019中运行QT UI
- QT通过C++添加映射QML项目
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 使用Qt C++计算类似Git的SHA1哈希
- Qt focusObjectChanged example?
- 如何在cpp文件之间切换窗口?在Qt中
- Qt和C++:将QLineEdit添加到QTabWidget中
- 从数据库实时显示QT c++中的数据
- Qt Quick-如何仅从c++代码与qml属性交互
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 如何在Qt中取消捕获字符串
- Qt SQLite没有查询或参数计数不匹配
- Qt SQlite无法创建表