I have my MainWindow with a GraphicsView on which I want to draw a QRubberBand using MouseEvents. Therefore I created a custom GraphicsView class where I have the MouseEvents, however since I am a beginner, I don't know how to connect everything to the MainWindow.
Here's what I got so far:
mousegraphics.h (custom)
#ifndef MOUSEGRAPHICS_H
#define MOUSEGRAPHICS_H
#include <QGraphicsView>
#include <QWidget>
#include <QMainWindow>
#include <QRubberBand>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QMouseEvent>
#include <QEvent>
class MouseGraphics : public QGraphicsView
{
public:
MouseGraphics(QWidget* parent = nullptr);
public slots:
void mousePressEvent(QMouseEvent* e);
void mouseMoveEvent(QMouseEvent* e);
void mouseReleaseEvent(QMouseEvent* e);
private:
QRubberBand* rb = nullptr;
// Coordinates
QPoint origin, dest;
};
#endif // MOUSEGRAPHICS_H
mousegraphics.cpp
#include "mousegraphics.h"
MouseGraphics::MouseGraphics(QWidget* parent) : QGraphicsView(parent)
{
}
void MouseGraphics::mousePressEvent(QMouseEvent *e)
{
origin = e->pos();
if(!rb)
{
rb = new QRubberBand(QRubberBand::Line, this);
}
rb->setGeometry(QRect(origin, QSize()));
rb->show();
}
void MouseGraphics::mouseMoveEvent(QMouseEvent *e)
{
rb->setGeometry(QRect(origin, e->pos()).normalized());
}
void MouseGraphics::mouseReleaseEvent(QMouseEvent *e)
{
rb->hide();
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QRubberBand>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QMouseEvent>
#include <QEvent>
#include "mousegraphics.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void mousePressEvent(QMouseEvent *e);
void mouseMoveEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
you should create one class that inherits from
QGraphicsView
.because you need
mousePressEvent
,mouseReleaseEvent
,mouseMoveEvent
of QGraphicsView.Then in MainWindow, you need one
QGraphicsScene
object and I create oneQGridLayout
and with theaddWidget
function add my QGraphicsView object to MainWindow UI.So I do this :
In graphicsview.h:
graphicsview.cpp :
In mainwindow.h :
In mainwindow.cpp :
The result is this
: