如何获取QGraphicWidget的位置坐标?

时间:2018-08-03 22:01:37

标签: c++ qt

我在QGraphicsWidget内的QGraphicsScene内有一个可移动标签,就像这样

QLabel *SelectLabel = new QLabel("Select This");

QGraphicsWidget* ParentWidget = new QGraphicsWidget();
ParentWidget->setFlags (QGraphicsItem::ItemIsMovable);

GraphicsScene->addItem(ParentWidget);


QGraphicsProxyWidget *proxy = MainScene->addWidget(SelectLabel);
proxy->setParentItem(ParentWidget);

这使我可以在QGraphicsArea内部自由移动(按住鼠标左键并拖动)标签。但是,我需要一种确切知道何时将标签/ QGraphicsWidget移至何处的方法。搜索之后,我发现了QGraphicsItem::ItemPositionChange标志,并尝试在->setFlag()中进行设置,并像下面这样应用广告位:

connect(ParentWidget, SIGNAL(moveEvent(QGraphicsSceneMoveEvent*)),
             this,    SLOT(labelPositionChange()));

但是然后我得到了错误:

QObject::connect: No such signal 
QGraphicsWidget::moveEvent(QGraphicsSceneMoveEvent*)

那么,有人可以告诉我如何获取QGraphicsWidget的移动事件吗?谢谢。

1 个答案:

答案 0 :(得分:1)

moveEvent不是信号。这是一个事件处理程序,旨在在派生类中重新实现。 las,您想要一些信号:QGraphicsObject::xChangedQGraphicsObject::yChanged

在下面的完整示例中,一个文本项用于显示位置。设置了场景对齐方式和矩形,以使场景不会相对于视图移动,因此文本在视图中保持固定。

screenshot

// https://github.com/KubaO/stackoverflown/tree/master/questions/graphics-widget-move-signals-51680570
#include <QtWidgets>

int main(int argc, char *argv[]) {
   QApplication a(argc, argv);
   QGraphicsScene scene;
   QGraphicsView view(&scene);
   view.setAlignment(Qt::AlignLeft | Qt::AlignTop);
   scene.setSceneRect(0, 0, 1, 1);

   QGraphicsWidget parent;
   parent.setPos(150, 100);
   QLabel label("Select This");
   label.setContentsMargins(10, 10, 10, 10);
   auto *proxy = scene.addWidget(&label);
   proxy->setParentItem(&parent);
   parent.setFlags(QGraphicsItem::ItemIsMovable);
   scene.addItem(&parent);

   QGraphicsTextItem text;
   scene.addItem(&text);
   auto const updateText = [&] {
      text.setPlainText(QString("%1, %2").arg(parent.x()).arg(parent.y()));
   };
   QObject::connect(&parent, &QGraphicsObject::xChanged, &text, updateText);
   QObject::connect(&parent, &QGraphicsObject::yChanged, &text, updateText);
   updateText();

   view.setMinimumSize(320, 320);
   view.show();
   return a.exec();
}