【问题标题】:Why QStandardItemModel 's member function children().size()return 0,while function hasChildren() return true?为什么 QStandardItemModel 的成员函数 children().size() 返回 0,而函数 hasChildren() 返回 true?
【发布时间】:2016-01-04 01:53:38
【问题描述】:

_inputfileModelQStandardItemModel 类型的指针,我想使用它的成员函数children() 来获取子项。但是在下面的代码中, int childrenNum = _inputfileModel->children().size(); childrenNum 的结果不是 1 而是 0。但是当我使用 hasChildren() 时,返回值为 true。谁能解释为什么?函数children() 是返回顶级子级还是所有子级?

void InputTree::addTreeNode(TreeNode &node){  

    QStringList inputImgList = node.picturePathList;  
    int num = inputImgList.size();  
    if( num < 1){ return ;}  
    QStandardItem *fatherItem = new QStandardItem;  
    fatherItem->setIcon(node.fatherIcon);  
    fatherItem->setText(node.fatherNodeName);  
    fatherItem->setData(FOLDER,ItemTypeRole);  

    for( int i = 0; i < num; ++i)
    {
        QStandardItem *pictureItem = new QStandardItem;
        pictureItem->setText(node.imageNodeName.at(i));
        pictureItem->setIcon(node.imgIcon);
        pictureItem->setData(PICTURE,ItemTypeRole);
        fatherItem->appendRow(pictureItem);
    }
    _inputfileModel->appendRow(fatherItem);
    bool has_child  = false;
    has_child = _inputfileModel->hasChildren();
    int childrenNum = _inputfileModel->children().size();
}

【问题讨论】:

    标签: c++ qt qt4


    【解决方案1】:

    只需阅读文档:

    bool QAbstractItemModel::hasChildren(const QModelIndex & parent = QModelIndex()) 常量

    如果父母有孩子,则返回真;否则返回 false。

    在父级上使用 rowCount() 来找出子级的数量。

    那么孩子呢:

    const QObjectList & QObject::children() const

    返回子对象列表。

    这不是你真正想要的。

    所以你应该使用QStandardItemModel::rowCount 而不是children()

    【讨论】:

      猜你喜欢
      • 2015-06-21
      • 1970-01-01
      • 2023-02-11
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2018-11-09
      相关资源
      最近更新 更多