如何在图形视图上移动 qwidget?

How to move qwidget on Graphics View?

QGraphicsView 我设置了 QGraphicsScene。我通过 QGraphicsProxy 小部件添加了一个 QDial 对象。如何移动 QDial 对象?

    QDial *dial = new QDial;// dial object
    dial->setGeometry(event->pos().x(),event->pos().y(),80,80);// placing on mouse position
    QSizeGrip * sizeGrip = new QSizeGrip(dial);

    QHBoxLayout *layout = new QHBoxLayout(dial);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(sizeGrip, 0, Qt::AlignRight | Qt::AlignBottom);

    QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget();
    proxy->setWidget(dial);
    proxy->setFlag(QGraphicsItem::ItemIsMovable,true);
    scene->addItem(proxy);

QDial 放入 QGraphicsProxyWidget 只是第一步。

由于代理不支持移动,您可以将其放入QGraphicsItem(例如矩形)并使用它来移动其中包含QDial的代理:

QDial *dial = new QDial();

QGraphicsRectItem* movableGraphicsItem = scene->addRect(event->pos().x(), event->pos().y(), 80, 80);
movableGraphicsItem->setFlag(QGraphicsItem::ItemIsMovable, true);
movableGraphicsItem->setFlag(QGraphicsItem::ItemIsSelectable, true);

QGraphicsProxyWidget* proxy = scene->addWidget(dial);
proxy->setPos(event->pos().x(), event->pos().y() + movableGraphicsItem->rect().height());
proxy->setParentItem(movableGraphicsItem);

movableGraphicsItem->setRotation(180); // Test by rotating the graphics item

我没有对此进行测试,您可能需要尝试使用您正在使用的尺寸、位置、布局和尺寸控制,但这是您可以开始的基础。

在此代码中,QGraphicsWidget 是 GraphicItem,通过将其设为小部件的父级,您可以将小部件移动到 scene.setflags 可移动的位置。

   QDial *dial = new QDial;// dial object
   dial->setGeometry(event->pos().x(),event->pos().y(),80,80);// placing on mouse position
   QSizeGrip * sizeGrip = new QSizeGrip(dial);

   QHBoxLayout *layout = new QHBoxLayout(dial);
   layout->setContentsMargins(0, 0, 0, 0);
   layout->addWidget(sizeGrip, 0, Qt::AlignRight | Qt::AlignBottom);

   QGraphicsWidget* parentWidget = new QGraphicsWidget();//make parent of widget
   parentWidget->setCursor(Qt::SizeAllCursor);
   parentWidget->setGeometry(event->scenePos().x(),event->scenePos().y(),width.toInt(), height.toInt());
   parentWidget->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable );
   addItem(parentWidget);

   QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget();
   proxy->setWidget(dial);
   proxy->setParentItem(parentWidget);