我拿一个非常简单的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"
}
}发布于 2014-07-01 19:19:54
cell->setParent(this);应该是
cell->setParentItem(this);可视父级的概念与QObject父级的概念不同。项目的可视父项可能不一定与其对象父级相同。有关更多细节,请参见QtQuick中的可视化父级。
这些资料摘自:
http://qt-project.org/doc/qt-5/qquickitem.html#parent-prop
https://stackoverflow.com/questions/24516973
复制相似问题