重写QGraphicView类实现在view控件上显示十字标线(解决QGraphicView重写qpaintevent无效的问题)

645 阅读1分钟

在这里插入图片描述
在我的代码里界面上放了一个qgraphicview,然后设置qgraphicview的场景QGraphicsScene,然后在QGraphicsScene里面放item(也就是上图显示的黑色线条)
我的需求是在view控件区域显示十字标辅助线
操作步骤如下:
1.重写一个类cusView继承自QGraphicsView
2.重写paintEvent函数,这个函数里写绘制十字线的代码。
3.重写mousemove函数,在里面调用this->scene()->update();目的是触发paintevent事件
具体重写的cusView类代码如下:
cusview.h头文件:

#ifndef CUSVIEW_H
#define CUSVIEW_H

#include <QObject>
#include <QGraphicsView>
#include <QMouseEvent>
class cusView:public QGraphicsView
{
    Q_OBJECT
public:
    cusView(QWidget *parent = nullptr);
    cusView(QGraphicsScene *scene, QWidget *parent = nullptr);
    ~cusView();
    void paintEvent(QPaintEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    QPoint mousePt;
};

#endif // CUSVIEW_H

cusview.cpp源文件:

#include "cusview.h"

cusView::cusView(QWidget *parent):mousePt(QPoint(-10,-10))
{
    this->setParent(parent);
    this->setMouseTracking(true);//为了让本控件实时响应鼠标移动事件,不加这一行的话,只有当鼠标点击的时候才会响应鼠标移动事件
}

cusView::cusView(QGraphicsScene *scene, QWidget *parent):mousePt(QPoint(-10,-10))
{
    this->setScene(scene);
    this->setParent(parent);
    this->setMouseTracking(true);//为了让本控件实时响应鼠标移动事件
}

cusView::~cusView()
{

}

void cusView::paintEvent(QPaintEvent *event)
{
    QPainter paint(this->viewport());//这行很重要,没有这行的话,绘制出来的东西都会被view里面的其他东西遮住
    QPen pen(Qt::blue,2);
    paint.setPen(pen);
    QPainterPath path;
    path.moveTo(mousePt.x(),0);
    path.lineTo(mousePt.x(),this->height());
    path.moveTo(0,mousePt.y());
    path.lineTo(this->width(),mousePt.y());
    paint.drawPath(path);
    QGraphicsView::paintEvent(event);
}

void cusView::mouseMoveEvent(QMouseEvent *event)
{
    mousePt = event->pos();
    this->scene()->update();
}

调用本类的界面代码如下: 头文件:

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QFile>
#include <QGraphicsLineItem>
#include <QGraphicsItem>
#include <QGraphicsView>
#include <QGraphicsSceneContextMenuEvent>
class QGraphicsScene;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
    void run();
    void mouseDoubleClickEvent(QMouseEvent *event);
    void contextMenuEvent(QContextMenuEvent *event);
    virtual void resizeEvent(QResizeEvent *event);
    void    getScaleSig(qreal topleftScale,qreal bottomleftScale);
private:
    //void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = Q_NULLPTR */);
private slots:
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();
    void on_pushButton_3_clicked();
    void on_pushButton_4_clicked();
private:
    Ui::Widget *ui;
    QFile aFile;
    QDataStream aStream;
    QDataStream bStream;
    int location =0;
    QGraphicsScene *m_scene;
    bool    m_bRotate;
};
#endif // WIDGET_H