开发者

A question about 'itemChange()' of QGraphicsItem

开发者 https://www.devze.com 2023-03-26 22:36 出处:网络
In the function of itemChange, first ,I get the child item that will be added, then I use dynamic_cast cast it to \'MyItem\', but the cast always fail.

In the function of itemChange, first ,I get the child item that will be added, then I use dynamic_cast cast it to 'MyItem', but the cast always fail.

 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(c开发者_如何学运维hange,value);
}

Thanks very much!


Note the comment on 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 can also fail if the object is not fully constructed. (I don't quite understand the spec on this, but there are some cases where it will, some where it will not.) If you set the parent after constructing the item, it will work:

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


Try using qgraphicsitem_cast

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号