【问题标题】:Accessing methods of a subclassed QGraphicsRectItem object访问子类 QGraphicsRectItem 对象的方法
【发布时间】:2015-12-28 10:28:51
【问题描述】:

我对 QGraphicsRectItem 进行了子类化,命名为 ResizableRectItem。我添加了一个新成员(int index)和两个方法(getIndex() 和 setIndex())。 我将 ResizableRectItems 添加到 QGraphicsScene

ResizableRectItem* item1 = new ResizableRectItem(selrect.normalized());
scene()->addItem(item1);

稍后我必须调用 getIndex() 方法,但我只能通过场景() 的 items() 访问项目,但是

int idx = scene()->items().at(0)->getIndex();

不正确,因为 scene()->items() 是 QGraphicsItem 并且没有 getIndex() 方法。 什么是正确的解决方案? 谢谢!

【问题讨论】:

    标签: c++ qt qgraphicsscene


    【解决方案1】:

    什么是正确的解决方案?

    如果你能重新思考你代码中的逻辑,这样你就不必依赖ResizableRectItem的接口,那将是最好的。

    如果你不能这样做,那么你需要使用dynamic_cast

    QGraphicsRectItem* gitem = scene()->items().at(0);
    ResizableRectItem* item = dynamic_cast<ResizableRectItem*>(gitem);
    if ( item != nullptr )
    {
       int idx = item->getIndex();
    }
    

    【讨论】:

    • 谢谢,它可以工作(如果我写的是 QGraphicsItem 而不是 QGraphicsRectItem)。我重新思考了我的逻辑,我注意到 QGraphicsItem 有一个名为 data 的成员(使用 getter/setter 方法),我可以在其中存储任意数据,所以我不需要创建自己的成员 index
    【解决方案2】:

    您可以尝试将对象转换为您的数据类型,并在成功时对其进行操作。像这样:

    ResizableRectItem* item = qobject_cast<ResizableRectItem*>(scene()->items().at(0)); 
    if (item)
    {
       int idx = item->getIndex();
    }
    

    更多信息http://doc.qt.io/qt-5/metaobjects.html

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2021-03-01
      • 2019-06-10
      相关资源
      最近更新 更多