在QGraphicsView / QGraphicsScene中移动QGraphicsProxyWidget中的嵌入式窗口小部件

时间:2016-04-24 16:56:17

标签: c++ qt qgraphicsview qgraphicsscene

我试图用鼠标移动QGraphicsView上的按钮但不是 工作,有些人可以帮我解决问题吗?

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  MainWindow windows;
  QGraphicsScene scene(&windows);
  QGraphicsView view(&scene, &windows);
  QGraphicsProxyWidget *proxy = scene.addWidget(new QPushButton("MOVE IT"));
  proxy->setFlags(QGraphicsItem::ItemIsMovable |
                  QGraphicsItem::ItemIsSelectable |
                  QGraphicsItem::ItemSendsGeometryChanges |
                  QGraphicsItem::ItemSendsScenePositionChanges);
  windows.setCentralWidget(&view);
  windows.show();
  return app.exec();
}

PD:请忽略我的内存泄漏。

1 个答案:

答案 0 :(得分:2)

QGraphicsProxyWidget只是任何普通QWidget的包装器,因此它没有自己的表面可供点击。所有点击事件都由嵌套的QPushButton使用。

在下面的示例中,我添加了一个额外的parentWidget,其面积更大:

#include <QtCore>
#include <QtGui>
#include <QtWidgets>

int
main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  QGraphicsScene scene;
  QGraphicsView  view(&scene);

  QGraphicsWidget* parentWidget = new QGraphicsWidget();

  // make parent widget larger that button
  parentWidget->setMinimumSize(QSizeF(100, 30));
  parentWidget->setFlags(QGraphicsItem::ItemIsMovable);
  parentWidget->setAutoFillBackground(true);
  scene.addItem(parentWidget);

  QGraphicsProxyWidget *proxy =
    scene.addWidget(new QPushButton("MOVE IT"));
  // put your wrapped button onto the parent graphics widget
  proxy->setParentItem(parentWidget);

  view.setFixedSize(QSize(600, 400));
  view.show();
  return app.exec();
}
相关问题