QGraphicsObject和QGraphicsItem
时间: 2023-05-25 18:02:54 浏览: 386
QGraphicsObject和QGraphicsItem都是Qt5中的图形对象,但是它们并不相同。
QGraphicsItem是Qt图形框架中的一个基础类,是所有可展示的图形项的基类,包括了常见图形项如线条、矩形、椭圆、多边形、文本等。QGraphicsItem的作用是封装了图形项的位置、大小、外观和交互行为等属性,并提供了一些操作这些属性的方法。
QGraphicsObject是QGraphicsItem的派生类,虽然功能与QGraphicsItem类似,但QGraphicsObject提供了更多高级的特性。比如,它可以利用Qt的元对象系统,并支持Qt的信号和槽机制,使得图形对象与应用程序的其他组件之间的交互更加方便。此外,QGraphicsObject还可以支持事件、动画、属性动画等高级特性。
总的来说,QGraphicsItem通常用于绘制简单的图形对象,而QGraphicsObject则更多地用于创建交互式的复杂的图形对象。
相关问题
QGraphicsItem画五角星 C++
以下是一个画五角星的QGraphicsItem示例代码:
```cpp
#include <QPainter>
#include <QPointF>
#include <QVector>
class StarItem : public QGraphicsItem
{
public:
StarItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent) {}
QRectF boundingRect() const override
{
return QRectF(-50, -50, 100, 100);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
Q_UNUSED(option);
Q_UNUSED(widget);
QVector<QPointF> points;
const double pi = 3.14159265358979323846;
const double deg = pi / 180.0;
const double angle = 36.0 * deg;
const double radius = 50.0;
for (int i = 0; i < 5; ++i)
{
const double x = radius * qCos(angle * i);
const double y = radius * qSin(angle * i);
points << QPointF(x, y);
}
painter->drawPolygon(QPolygonF(points));
}
};
```
在场景中添加该项:
```cpp
StarItem *starItem = new StarItem();
starItem->setPos(100, 100);
scene->addItem(starItem);
```
注意,该示例代码使用的是QGraphicsItem的paint()函数进行绘制。如果您使用的是QGraphicsObject,可以在其子类中重写paintEvent()函数进行绘制。
先执行QGraphicsItem鼠标松开事件接着执行QGraphicsView鼠标松开事件 C++
在Qt中,QGraphicsView继承自QWidget,而QGraphicsItem继承自QGraphicsObject。因此,当在QGraphicsView中鼠标松开时,会首先调用QGraphicsView的mouseReleaseEvent(),然后再调用QGraphicsScene的mouseReleaseEvent(),最后才调用QGraphicsItem的mouseReleaseEvent()。
如果你想先执行QGraphicsItem的鼠标松开事件,可以使用eventFilter()函数来拦截QGraphicsView的鼠标松开事件,并在其中调用QGraphicsItem的mouseReleaseEvent()。以下是一个示例:
```cpp
bool MyGraphicsItem::eventFilter(QObject* obj, QEvent* event)
{
if(event->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
if(mouseEvent->button() == Qt::LeftButton)
{
mouseReleaseEvent(mouseEvent);
return true;
}
}
return QObject::eventFilter(obj, event);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent* event)
{
QGraphicsView::mouseReleaseEvent(event);
}
void MyGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
QGraphicsScene::mouseReleaseEvent(event);
}
void MyGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
// 处理鼠标松开事件
}
```
在这个示例中,我们重写了QGraphicsItem的eventFilter()函数,在其中拦截QGraphicsView的鼠标松开事件,并调用QGraphicsItem的mouseReleaseEvent()函数处理事件。在QGraphicsView和QGraphicsScene中,我们只需要调用父类的mouseReleaseEvent()函数即可。