im trying to create a selection rectangle over a graphicsView widget but the rectangle thats created is all offset and moves the initial image previous putted in there. The program basiclly uses the left and right click of the mouse, both set coordinates and draw a rectangle.
This is my MasterChief.cpp
#include "MasterChief.h"
MasterChief::MasterChief(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
images();
}
MasterChief::~MasterChief()
{}
void MasterChief::mousePressEvent(QMouseEvent* event) {
switch (event->button()) {
case Qt::LeftButton:
firstcoordinates = event->pos();
break;
case Qt::RightButton:
secondcoordinates = event->pos();
break;
}
if ((firstcoordinates != QPoint(-1,-1)) && (secondcoordinates != QPoint(-1,-1))){
scene->clear();
images();
rectangle = new QGraphicsRectItem(firstcoordinates.x(), firstcoordinates.y(), secondcoordinates.x(), secondcoordinates.y()); // (x, y, width, height)
rectangle->setBrush(QBrush(Qt::blue)); // Set the rectangle's brush color (e.g., blue)
scene->addItem(rectangle);
}
}
void MasterChief::images (){
ui.layout->addWidget(graphicsView);
QPixmap pixmap("C:/Users/User/Desktop/Fac/sistca/ArduinoFotos/arduinoidesetup1.png");
QGraphicsPixmapItem* pixmapItem = new QGraphicsPixmapItem(pixmap);
scene->addItem(pixmapItem);
graphicsView->setScene(scene);
graphicsView->show();
}
And my MasterChief.h
#pragma once
#include <QGraphicsView>
#include <QMouseEvent>
#include <QDebug>
#include <QtWidgets/QWidget>
#include "ui_MasterChief.h"
#include <QAbstractButton>
#include <QPushButton>
#include <QFileDialog>
#include <QProgressDialog>
#include <QDirIterator>
#include <QMenu>
#include <QDir>
#include <QPoint>
#include <QLabel>
#include <QFileInfo>
#include <QGuiApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPixmap>
#include <QImage>
#include <QImageReader>
#include <QInputDialog>
#include <QVBoxLayout>
#include <QLayout>
#include <QInputDialog>
#include <QTranslator>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QDialog>
#include <QMouseEvent>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
class MasterChief : public QWidget
{
Q_OBJECT
public:
MasterChief(QWidget *parent = nullptr);
~MasterChief();
QPoint secondcoordinates = QPoint(-1,-1);
QPoint firstcoordinates = QPoint(-1,-1);
QGraphicsRectItem* rectItem= nullptr;
QGraphicsScene* scene = new QGraphicsScene;
QGraphicsView* graphicsView = new QGraphicsView(this);
QGraphicsRectItem* rectangle;
private slots:
void images();
void mousePressEvent(QMouseEvent* event);
private:
Ui::MasterChiefClass ui;
};
I think the problem may be with the resolution of the graphic view and the input in the scene. Im selecting some coorrdinates that inside the graphicView are in another place.
Vasco Costa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.