qt - 关于QGraphicsItem的 'itemChange()'的一个问题

标签 qt qgraphicsitem

在 itemChange 的函数中,首先,我获取将要添加的子项目,然后我使用 dynamic_cast 将其转换为“MyItem”,但转换总是失败。

 QVariant MyItem::itemChange ( GraphicsItemChange change, const QVariant & value )
{

if (change==ItemChildAddedChange)
{
  QGraphicsItem* item=value.value<QGraphicsItem*>();
if (item)
{
     MyItem* myItem=dynamic_cast<MyItem*>(item);//myItem always be NULL,
//although I know the item is 'MyItem' type.
     if (myItem)
      {
       qDebug()<<"successful!";
       }
       }
}
return QGraphicsItem::itemChange(change,value);
}

非常感谢!

最佳答案

注意 itemChange 上的注释:

Note that the new child might not be fully constructed when this notification is sent; calling pure virtual functions on the child can lead to a crash.

如果对象未完全构建,

dynamic_cast 也可能失败。 (我不太明白这方面的规范,但有些情况下会,有些情况下不会。)如果你在构建项目之后设置父级,它将起作用:

#include <QtGui>

class MyGraphicsItem : public QGraphicsRectItem {
public:
  MyGraphicsItem(QGraphicsItem *parent, QGraphicsScene *scene)
    : QGraphicsRectItem(0.0, 0.0, 200.0, 200.0, parent, scene) {
    setBrush(QBrush(Qt::red));
  }
protected:
  QVariant itemChange(GraphicsItemChange change, const QVariant &value) {
    if (change == QGraphicsItem::ItemChildAddedChange) {
      QGraphicsItem* item = value.value<QGraphicsItem*>();
      if (item) {
        MyGraphicsItem* my_item=dynamic_cast<MyGraphicsItem*>(item);
        if (my_item) {
          qDebug() << "successful!";
        }
      }
    }
    return QGraphicsRectItem::itemChange(change, value);
  }
};

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

  QGraphicsScene scene;
  MyGraphicsItem *item = new MyGraphicsItem(NULL, &scene);

  // This will work.
  MyGraphicsItem *item2 = new MyGraphicsItem(NULL, &scene);
  item2->setParentItem(item);

//  // This will not work.
//  MyGraphicsItem *item2 = new MyGraphicsItem(item, &scene);

  QGraphicsView view;
  view.setScene(&scene);
  view.show();

  return app.exec();
}

关于qt - 关于QGraphicsItem的 'itemChange()'的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6981310/

相关文章:

c++ - 从Qt中的静态类方法发送信号

c++ - 如何在 Qt 中执行复杂的 linux 命令?

c++ - 为什么 QFontMetrics::maxWidth 会返回这么大的值?

qt - 如何更改 QGraphicsScene 上 QGraphicsItem 的 borderingRect() 的位置?

python - 如何在 QGraphicsView 中绘制折线 ("open polygon")

qt - 如何将 mousePressEvent() 传播到一组 QGraphicsItem?

javascript - 在 Qt 中将 C++ 对象暴露给 Javascript

Qt Creator qml : Use (extra) Qt Components library (ubuntu)

qt - 我可以在 QGraphicsItem 中获取鼠标事件吗?

c++ - 拖动释放后如何适本地获得 QGraphicsRectItem 的位置?