无法在运行时通过 QQmlComponent 明显实例化

Can't visibly instantiate at runtime via QQmlComponent

本文关键字:QQmlComponent 实例化 运行时      更新时间:2023-10-16

我拿一个非常简单的QML样本开玩笑,它最终应该是某种棋盘,但由于某些原因,我无法在运行时正确添加单元格。单元使用C++类(扩展QQuickItemBasicCell(定义,并且可以使用Qml(cell.qml(:进行样式设置

BasicCell {
    width: 32
    height: 32
    Rectangle {
        anchors.fill : parent
        color : "green"
    }
}

我使用QQmlComponent在运行时构建这个"样式"BasicCell:的实例

QQmlComponent cellComponent(qmlEngine(), cellUrl, this);

// Make sure we could actually load that QML component
if (cellComponent.status() != QQmlComponent::Ready)
{
  std::cerr << "Error loading cell.qml:" << std::endl;
  for (const auto& err : cellComponent.errors())
  {
    std::cerr << "  " << err.toString().toStdString() << std::endl;
  }
}
for (int x = 0; x < mNumTiles.width(); ++x)
{
  for (int y = 0; y < mNumTiles.height(); y++)
  {
    BasicCell* cell = qobject_cast<BasicCell*>(cellComponent.create());
    cell->setParent(this);
    cell->setSize(QSize(tileSize(), tileSize()));
    cell->setGridPos(QPoint(x, y));
    childItems().append(cell);
    mCells.insert(cell->gridPos(), cell);
  }
}

当使用QML调试器时,我可以看到我最终得到了"正确"的层次结构:

Game
  BasicCell
     Rectangle
  BasicCell
     Rectangle
  ...

但我什么都看不见。。。我反复检查:所有这些矩形和基本单元格都设置了适当的大小。

越来越沮丧的是,我终于从cell.qml中复制了代码,并将其作为直接子级粘贴到Board.qml中。令我惊讶的是,这使单元格完全符合我的预期。

与QML中的这种实例化不同,我在使用QQmlComponent时缺少了什么?

Game
{
    // Should be created at runtime using QQmlComponent
    BasicCell {
        width: 32
        height: 32
        Rectangle {
            anchors.fill: parent
            color : "green"
        }
        gridPos: "0,0"
    }
}
cell->setParent(this);

应该是

cell->setParentItem(this);

视觉父对象的概念与QObject的概念不同父母亲项目的视觉父项可能不一定与其相同对象父对象。有关更多信息,请参阅Qt Quick中的概念-Visual Parent详细信息。

摘自:

http://qt-project.org/doc/qt-5/qquickitem.html#parent-道具