在 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/