QGraphicsItem是Qt中用于表示2D图形元素的基类,它提供了许多重要的特性和方法,使得开发者能够创建和管理复杂的图形界面。以下是QGraphicsItem的一些关键特性和方法的详细介绍:
关键特性
- 坐标系统:每个QGraphicsItem都有自己的本地坐标系统,可以通过变换(平移、旋转、缩放)来调整其在场景中的位置和方向。
- 层级和群组:QGraphicsItem可以组织成树状结构,其中每个项可以有零个或多个子项,并且只有一个父项。这允许创建复杂的层级和群组。
- 碰撞检测:QGraphicsItem提供了碰撞检测功能,可以用来确定两个项是否相交。
- 事件处理:QGraphicsItem可以接收和处理各种事件,如鼠标点击、移动、滚轮滚动和键盘事件。
- 选择和焦点:QGraphicsItem可以被选择,并且可以拥有键盘焦点,这使得它们能够响应用户输入。
- 缓存和状态:为了提高性能,QGraphicsItem支持缓存其外观,并且可以有不同的状态(如正常、悬停、按下等)。
常用方法
- QGraphicsItem(QGraphicsItem *parent = nullptr):构造函数,可以指定父项。
- virtual QRectF boundingRect() const:必须由子类实现的纯虚函数,返回项的边界矩形。
- virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr):必须由子类实现的纯虚函数,用于自定义项的渲染逻辑。
- QPointF pos() const:返回项在其父项坐标系中的位置。
- void setPos(const QPointF &pos):设置项在其父项坐标系中的位置。
- QGraphicsItem *parentItem() const:返回项的父项。
- QList<QGraphicsItem *> children() const:返回项的所有直接子项的列表。
- virtual bool contains(const QPointF &point) const:如果指定的点在项的边界矩形内,则返回true。
- virtual QPainterPath shape() const:返回项的形状路径,用于更精确的碰撞检测。
- virtual bool collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const:如果项与另一个项发生碰撞,则返回true。
- virtual QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value):当项的属性即将发生变化时,会发出此信号。
信号和槽
- void itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value):当项的属性即将发生变化时,会发出此信号。
- void hoverEnterEvent(QGraphicsSceneHoverEvent *event):当鼠标光标进入项的区域时,会调用此槽函数。
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event):当鼠标光标在项的区域上移动时,会调用此槽函数。
- void hoverLeaveEvent(QGraphicsSceneHoverEvent *event):当鼠标光标离开项的区域时,会调用此槽函数。
- void mousePressEvent(QGraphicsSceneMouseEvent *event):当鼠标按钮在项上按下时,会调用此槽函数。
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event):当鼠标在项上移动时,会调用此槽函数。
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event):当鼠标按钮在项上释放时,会调用此槽函数。
使用示例
下面是一个更完整的自定义QGraphicsItem子类的示例,它演示了如何响应鼠标事件:
class ClickableItem : public QGraphicsItem
{
public:
ClickableItem() {}
QRectF boundingRect() const override
{
return QRectF(0, 0, 100, 100); // 假设项的大小为100x100
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setBrush(Qt::blue); // 设置填充颜色为蓝色
painter->drawRect(boundingRect()); // 绘制矩形
}
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
if (event->button() == Qt::LeftButton)
{
// 处理左键点击事件
qDebug() << "Left button clicked!";
}
}
};
// 在某个地方创建和使用ClickableItem
QGraphicsScene *scene = new QGraphicsScene();
ClickableItem *item = new ClickableItem();
item->setPos(100, 100); // 设置项的位置
scene->addItem(item); // 将项添加到场景中
在这个示例中,我们创建了一个名为ClickableItem的自定义图形项类,它继承自QGraphicsItem。我们重写了boundingRect()和paint()函数来定义项的几何形状和渲染逻辑。此外,我们还重写了mousePressEvent()函数来处理鼠标左键点击事件。
通过这些特性和方法,QGraphicsItem成为了构建复杂图形界面和交互式应用程序的强大工具。