【问题标题】:Own objects into QGraphicsScene将自己的对象放入 QGraphicsScene
【发布时间】:2012-01-02 21:07:53
【问题描述】:

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

#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;
}

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

【问题讨论】:

    标签: c++ qt qgraphicsview qgraphicsitem qgraphicsscene


    【解决方案1】:

    QGraphicsItem 已经支持在QGraphicsScene 内拖放移动。您只需要设置QGraphicsItem::ItemIsMovable 标志。

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

    【讨论】:

    • 似乎一旦设置好场景并绘制了我所有的自定义 QGraphicsItem,QGraphicsItem::itemChange() 就再也不会输入...
    • 已解决,必须设置这个标志:setFlag(QGraphicsItem::ItemSendsScenePositionChanges);
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      相关资源
      最近更新 更多