无法在运行时通过 QQmlComponent 明显实例化
Can't visibly instantiate at runtime via QQmlComponent
我拿一个非常简单的QML样本开玩笑,它最终应该是某种棋盘,但由于某些原因,我无法在运行时正确添加单元格。单元使用C++类(扩展QQuickItem
的BasicCell
(定义,并且可以使用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-道具
相关文章:
- 是否可以在编译时限制类的实例数?
- 拉帕克C++实矩阵反演
- specialized std::default_delete with QQmlComponent
- 在 Eigen3 中实现 Bartels-Stewart 算法 -- 仅实矩阵?
- 使用类进行实现时,递归打印C++中的链表
- C++中复向量与实向量的二维卷积
- 重新实现在nodejs中使用SHA2的旧c ++项目?
- 从文件中读取实值和虚值,并在 c++ 中使用复数类形成复变量
- 为什么"stdint.h"的实现在UINT8_C的定义上存在分歧?
- 当我将C++类拆分为标头和实现时,我得到了 20 个没有意义的编译器错误
- 来自模块项目的QQMLCOMPONENT
- C 中STD :: vector的压实bool功能
- 当中间类跳过实现时,在继承层次结构中执行哪种虚拟方法
- std::map 实现在 Linux 和 Windows 之间有所不同
- 如何计算实例数组中未删除的实例
- 是否可以在C++中制作一个可调用自身的实函数类型?
- 为什么偏移实现在 C 和 C++ 上奇怪地不同
- 如何从实双打的std::向量中填充复数双打的std::向量
- 如何在 Eigen3 库中高效提取复矩阵的实部/虚部?
- C/C++中固定长度实输入数据的高效二维FFT