2

我想有一个基于图像的拖放功能。如果我拖放一个图像,我想知道我选择并移动了哪个图像(一个简单的 std::string 可以唯一标识该图像所代表的对象)。我的想法是将我自己的对象(QPixmapItem)存储在 QGraphicsScene 中:

#ifndef QPIXMAPITEM_H
#define QPIXMAPITEM_H

#include <QGraphicsPixmapItem>
#include <QPoint>

class QPixmapItem : public QGraphicsPixmapItem
{
public:
    QPixmapItem(std::string path, std::string id, int x, int y);
    std::string getIdentifier (){return this->identifier;}
    QPoint getPosition () const{return this->position;}

private:
    std::string identifier;
    QPoint position;
};

#endif // QPIXMAPITEM_H

这是我用来将对象添加到场景中的方法:

void MainWindow::addPixmapItemToScene(std::string path, int x, int y)
{
    // generate pixmap item & add it to the scene
    QPixmapItem *item = new QPixmapItem(path, std::string("id123"), x, y);
    ui->roomView->scene()->addItem(item);

    // only update the affected area
    ui->roomView->updateSceneRect(item->pixmap().rect());
}

这是我尝试在 QMouseEvent 中“捕获”对象的方法:

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    std::cout << "mouse pressed" << std::endl;

    QGraphicsPixmapItem *currentItem = dynamic_cast<QGraphicsPixmapItem *>(childAt(event->pos()));
    if (!currentItem) {
        return;
    }
    std::cout << "item pressed" << std::endl;
}

对象被添加到场景中,但每当我按下它们时,最后一行(“按下的项目”)永远不会出现在屏幕上。

4

2 回答 2

1

QGraphicsItem已经支持在QGraphicsScene. 您所需要的只是设置QGraphicsItem::ItemIsMovable标志。

如果您想在发生这种情况时得到通知,QGraphicsItem::itemChange()请在您的 custom中覆盖QGraphicsItem

于 2012-01-03T05:00:14.530 回答
0

childAt() 不起作用,因为它返回一个 QWidget,并且 QGraphicsPixMapItems 不是 QWidgets(因此 childAt() 永远不会返回指向任何类型的 QGraphicsItem 的指针,即使它以某种方式返回,dynamic_cast 转换无论如何都会返回 NULL)。

为了获得与场景中指定点相交的 QGraphicsItems 列表,请在场景对象上调用QGraphicsScene::items()。然后遍历返回的列表,找出其中有哪些 QGraphicsPixMapItems(如果有)。

于 2012-01-02T21:47:31.497 回答