You are combining the boundingRect coordinates that are relative to the item with the coordinates relative to the scene. On the other hand, don't complicate creating a custom item, instead use a custom QGraphicsRectItem. Finally it is recommended that you establish a sceneRect.
component.h
#ifndef COMPONENT_H
#define COMPONENT_H
#include <QGraphicsRectItem>
class Component : public QGraphicsRectItem
{
public:
Component(unsigned int id, QString cname, QString ctype, QGraphicsItem *parent=nullptr);
private:
unsigned int m_id;
QString m_cname;
QString m_ctype;
};
#endif // COMPONENT_H
component.cpp
#include "component.h"
Component::Component(unsigned int id, QString cname, QString ctype, QGraphicsItem*parent):
QGraphicsRectItem(parent), m_id(id), m_cname(cname), m_ctype(ctype)
{
setRect(-40, -40, 80, 80);
setFlag(ItemIsMovable);
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->graphView->setContextMenuPolicy(Qt::CustomContextMenu);
scene = new QGraphicsScene();
ui->graphView->setScene(scene);
ui->graphView->setSceneRect(QRect(0, 0, 400, 400));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_graphView_customContextMenuRequested(const QPoint &pos)
{
QPointF pp = ui->graphView->mapToScene(pos);
Component* component = new Component(s, n, t);
scene->addItem(component);
component->setPos(pp);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…