C++ 如何正确地将小部件放置在鼠标右下方的QGraphicsView上?

C++ 如何正确地将小部件放置在鼠标右下方的QGraphicsView上?,c++,qt,qt5,qgraphicsscene,C++,Qt,Qt5,Qgraphicsscene,我一直在尝试使用QGraphicsView解决定位问题 从QListWidget拖动小部件并将其放入QGraphicsView后,它会到处跳跃 在另一位用户的帮助下,我一直试图解决的问题如下: 将小部件拖入QGraphicsView并放下后。它只是在随机的位置,必须注意检索它。这种行为对用户不友好,有时需要一点时间才能找到小部件 代码如下: 场景.h #ifndef SCENE_H #define SCENE_H #include <QGraphicsScene> class

我一直在尝试使用
QGraphicsView
解决定位问题

QListWidget
拖动小部件并将其放入
QGraphicsView
后,它会到处跳跃

在另一位用户的帮助下,我一直试图解决的问题如下: 将小部件拖入
QGraphicsView
并放下后。它只是在随机的位置,必须注意检索它。这种行为对用户不友好,有时需要一点时间才能找到小部件

代码如下:

场景.h

#ifndef SCENE_H
#define SCENE_H

#include <QGraphicsScene>

class Scene : public QGraphicsScene
{
public:
    Scene(QObject *parent = nullptr);

protected:
  void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
  void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
  void dropEvent(QGraphicsSceneDragDropEvent *event);
};

#endif // SCENE_H
另外一个尝试是提供
QPoint
事件->scenePos().toPoint()作为目标的合适选项,但不幸的是,这也没有解决问题:

for (const QString &tableType : rosTables) {
    if (tableType == "Images") {
        QPoint initPos(event->scenePos().toPoint()); // <-- Tried this too but no change
        auto *wgt = new CustomTableWidget;
        auto *proxyControl = addRect(0, 0, 0, 0, QPen(Qt::black),
                                     QBrush(Qt::darkGreen));
        auto *sizeGrip = new QSizeGrip(wgt);
        auto *layout = new QHBoxLayout(wgt);
} 
for(常量字符串和表类型:列表){
如果(表类型=“图像”){
QPoint initPos(事件->场景().toPoint());//
  • proxy->setPos(initPos.x(),initPos.y()+proxyControl->rect().height());
    更改为
    proxy->setPos(10,10);

  • 设置场景矩形:

     Scene::Scene(QObject *parent) :
         QGraphicsScene(parent)
     {
         setBackgroundBrush(Qt::lightGray);
         setSceneRect(0, 0, 1000, 1000);
     }
    
  • 设置视图对齐,例如在MainWindow.cpp中:

  • for (const QString &tableType : rosTables) {
        if (tableType == "Images") {
            QPoint initPos(event->scenePos().toPoint()); // <-- Tried this too but no change
            auto *wgt = new CustomTableWidget;
            auto *proxyControl = addRect(0, 0, 0, 0, QPen(Qt::black),
                                         QBrush(Qt::darkGreen));
            auto *sizeGrip = new QSizeGrip(wgt);
            auto *layout = new QHBoxLayout(wgt);
    } 
    
     Scene::Scene(QObject *parent) :
         QGraphicsScene(parent)
     {
         setBackgroundBrush(Qt::lightGray);
         setSceneRect(0, 0, 1000, 1000);
     }
    
     ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);