25'ten fazla konu seçemezsiniz
Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
|
- #include "mygraphicsview.h"
- #include <QMimeData>
- #include <QCursor>
- #include <QGraphicsScene>
- #include <QDebug>
-
- MyGraphicsView::MyGraphicsView(QWidget *parent)
- : QGraphicsView(parent)
- {
- setAcceptDrops(true);
- viewport()->setAcceptDrops(true);
- setRenderHint(QPainter::Antialiasing);
- setFocusPolicy(Qt::StrongFocus); // 让view能接收键盘事件
- }
-
- void MyGraphicsView::dragEnterEvent(QDragEnterEvent *event)
- {
- if (event->mimeData()->hasFormat("application/x-component"))
- event->acceptProposedAction();
- else
- event->ignore();
- }
-
- void MyGraphicsView::dragMoveEvent(QDragMoveEvent *event)
- {
- if (event->mimeData()->hasFormat("application/x-component"))
- event->acceptProposedAction();
- else
- event->ignore();
- }
-
- void MyGraphicsView::dropEvent(QDropEvent *event)
- {
- if (!event->mimeData()->hasFormat("application/x-component")) {
- event->ignore();
- return;
- }
-
- QString type = QString::fromUtf8(event->mimeData()->data("application/x-component"));
-
- QPointF scenePos = mapToScene(event->pos());
- Item *item = new Item(type);
- item->setPos(scenePos);
-
- if (scene())
- scene()->addItem(item);
-
- event->acceptProposedAction();
- }
-
- void MyGraphicsView::keyPressEvent(QKeyEvent *event)
- {
- if (event->key() == Qt::Key_Delete && scene()) {
- // 删除所有被选中的图元
- QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
- for (QGraphicsItem* item : selectedItems) {
- scene()->removeItem(item);
- delete item;
- }
- } else {
- QGraphicsView::keyPressEvent(event);
- }
- }
|