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



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);

在此代码中,QGraphicsWidget 是 GraphicItem 通过使 widget 的父级,您可以在 scene.setflags 上移动 widget 可移动。

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);

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

我还没有测试过这个,你可能不得不玩弄你正在使用的尺寸、位置、布局和尺寸握把,但这是你可以开始的基础。

最新更新