c++ qt继承QObject和QGraphicsItem画十字点、画矩形、画多边形、画直线卡尺,在同一个类中,而且可以通过鼠标滚轮缩放
时间: 2023-05-18 19:06:46 浏览: 353
可以通过以下代码实现:
```c++
#include <QtGui>
class MyGraphicsItem : public QObject, public QGraphicsItem
{
public:
MyGraphicsItem(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->setRenderHint(QPainter::Antialiasing);
painter->setPen(QPen(Qt::black, 2));
painter->drawLine(-50, 0, 50, 0);
painter->drawLine(0, -50, 0, 50);
painter->drawRect(-25, -25, 50, 50);
QPolygonF polygon;
polygon << QPointF(-30, 30) << QPointF(0, -30) << QPointF(30, 30);
painter->drawPolygon(polygon);
painter->setPen(QPen(Qt::red, 1, Qt::DashLine));
painter->drawLine(-50, 0, 50, 0);
painter->drawLine(0, -50, 0, 50);
}
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
m_lastPos = event->pos();
m_isDragging = true;
}
}
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override
{
if (m_isDragging) {
QPointF delta = event->pos() - m_lastPos;
setPos(pos() + delta);
m_lastPos = event->pos();
}
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
m_isDragging = false;
}
}
void wheelEvent(QGraphicsSceneWheelEvent *event) override
{
qreal factor = qPow(1.2, event->delta() / 240.0);
setScale(scale() * factor);
}
private:
QPointF m_lastPos;
bool m_isDragging = false;
};
```
在这个类中,我们继承了 QObject 和 QGraphicsItem,实现了 boundingRect() 和 paint() 函数来绘制图形,以及 mousePressEvent()、mouseMoveEvent()、mouseReleaseEvent() 和 wheelEvent() 函数来处理鼠标事件。在 paint() 函数中,我们绘制了十字点、矩形、多边形和直线卡尺,并使用 setPen() 函数设置了画笔的颜色、宽度和样式。在 mousePressEvent()、mouseMoveEvent() 和 mouseReleaseEvent() 函数中,我们处理了鼠标拖动事件,使图形可以被拖动。在 wheelEvent() 函数中,我们处理了鼠标滚轮事件,使图形可以被缩放。
阅读全文