Qt c++用QGraphicsItem类实现按下左键生成一个矩形跟着鼠标沿x轴移动 松开后小时
时间: 2024-03-28 20:41:59 浏览: 23
可以通过继承QGraphicsItem类来实现按下左键生成一个矩形跟着鼠标沿x轴移动的功能。具体实现步骤如下:
1. 定义一个MyRect类,继承QGraphicsItem类。
2. 在MyRect类中重写boundingRect()和paint()函数,分别用于绘制矩形和获取矩形的边界矩形。
3. 在MyRect类中重写mousePressEvent()和mouseReleaseEvent()函数,分别处理鼠标按下和松开事件,实现生成矩形并跟随鼠标移动的功能。
下面是完整的代码实现:
```cpp
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QMouseEvent>
#include <QPainter>
class MyRect : public QGraphicsItem
{
public:
MyRect(QGraphicsItem* parent = nullptr)
: QGraphicsItem(parent)
, m_rect(0, 0, 0, 0)
{
setAcceptHoverEvents(true);
}
QRectF boundingRect() const override
{
return m_rect;
}
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override
{
painter->drawRect(m_rect);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) override
{
if (event->button() == Qt::LeftButton)
{
m_rect.setTopLeft(event->pos());
m_rect.setBottomRight(event->pos());
update();
}
}
void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override
{
if (event->buttons() & Qt::LeftButton)
{
m_rect.setBottomRight(event->pos());
update();
}
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override
{
if (event->button() == Qt::LeftButton)
{
m_rect.setBottomRight(event->pos());
update();
}
}
private:
QRectF m_rect;
};
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
scene.setSceneRect(0, 0, 800, 600);
MyRect* rect = new MyRect;
scene.addItem(rect);
QGraphicsView view(&scene);
view.setRenderHint(QPainter::Antialiasing);
view.show();
return a.exec();
}
```
在这段代码中,我们定义了一个MyRect类,继承了QGraphicsItem类,并重写了boundingRect()、paint()、mousePressEvent()、mouseMoveEvent()和mouseReleaseEvent()函数。其中,boundingRect()用于获取矩形的边界矩形,paint()用于绘制矩形,mousePressEvent()、mouseMoveEvent()和mouseReleaseEvent()用于处理鼠标事件。
在mousePressEvent()函数中,我们检测到鼠标左键按下事件后,记录下矩形的左上角坐标,并将矩形的右下角坐标也设置为当前位置,然后调用update()函数通知系统重新绘制场景。
在mouseMoveEvent()函数中,我们检测到鼠标左键移动事件后,更新矩形的右下角坐标,并调用update()函数通知系统重新绘制场景。
在mouseReleaseEvent()函数中,我们检测到鼠标左键松开事件后,更新矩形的右下角坐标,并调用update()函数通知系统重新绘制场景。
最后,在main函数中,我们创建了一个QGraphicsScene对象和一个MyRect对象,并将MyRect对象添加到场景中。然后创建了一个QGraphicsView对象,并将其显示出来。这样,我们就可以在图形界面上按下左键生成一个矩形,并跟着鼠标沿x轴移动,松开鼠标后矩形消失了。