c++ qt继承QObject和QGraphicsItem画十字点、画直线、画线段,在同一个类中,而且可以通过void wheelEvent(QGraphicsSceneMouseEvent *event)重写来实现鼠标滚轮缩放
时间: 2023-05-21 09:00:56 浏览: 188
可以通过以下代码实现:
```cpp
#include <QtGui>
class CrossLine : public QObject, public QGraphicsItem
{
public:
CrossLine(QGraphicsItem *parent = nullptr) : QObject(parent), QGraphicsItem(parent) {}
QRectF boundingRect() const override
{
return QRectF(-50, -50, 100, 100);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
painter->drawLine(-50, 0, 50, 0);
painter->drawLine(0, -50, 0, 50);
painter->drawLine(-50, -50, 50, 50);
painter->drawLine(-50, 50, 50, -50);
}
void wheelEvent(QGraphicsSceneWheelEvent *event) override
{
if (event->delta() > 0) {
setScale(scale() * 1.1);
} else {
setScale(scale() / 1.1);
}
}
};
```
这个类继承了 QObject 和 QGraphicsItem,实现了 boundingRect 和 paint 函数来绘制十字线和直线段,同时重写了 wheelEvent 函数来实现鼠标滚轮缩放。
阅读全文