Qt4: Making “Simple Dom Model” editable; inserting rows

a 夏天 提交于 2019-12-23 04:14:13

问题


Basically, what I'm trying to achieve is combine "Editable Tree Model" and "Simple Dom Model" examples. So I'm having the latter as a base and I've copied the edit functions over there, changed the flags, setData, etc.

I've already had success with editing entries.

Now, I have a problem with adding rows to the model.

Specifically, when I use insertAfter function in QDomNode::parentNode(), the model gets updated only internally. When I collapse and expand the parent, the added node(s) are copies of the last nodes and are inserted in the end.

The only way I am able to get it right is save XML to QString and load it again into QDomModel and QTreeView. Then everything that has been inserted is where it should be. But then all the expanded states are lost! Not very user-friendly...


InsertAfter version:

// Get current index
QModelIndex currentTreeIdx = ui->treeView->selectionModel()->currentIndex();
// Get the node corresponding to that index
DomItem *itemRef = static_cast(currentTreeIdx.internalPointer());

QDomElement newParentTag;
QDomElement newTextTag;
QDomText newText;
// Create tags
newParentTag = model->domDocument.createElement("Parent");
newTextTag = model->domDocument.createElement("Child");
newText = model->domDocument.createTextNode("Child text data");
newTextTag.appendChild(newText);
newSubtitleTag.appendChild(newTextTag);
// Attempt to insert a new tag after the currently selected item
itemRef->node().parentNode().insertAfter(newParentTag, itemRef->node());

Now, I've tried adding rows like this instead of insertAfter:

model->insertRows(itemRef->row(), 1, currentTreeIdx.parent());

and the function being called is:

bool DomModel::insertRows(int position, int rows, const QModelIndex &parent){

    DomItem *parentItem = static_cast<DomItem*>(parent.internalPointer());   // reference item

    bool success;

    beginInsertRows(parent, position, position + rows - 1);
    success = parentItem->insertChildren(position, rows, 4);
    endInsertRows();

    return success;
}

This one should create a row. It does create an invisible parent that I can click on to expand. But this parent now contains a copy of the entire model...


It seems I have a problem with my insertChildren function. As it is now, it replaces the currently selected row with an empty one.

bool DomItem::insertChildren(int position, int count, int columns){
    if (position < 0 || position > childItems.size()){
        return false;
    }

    for (int row = 0; row < count; row++){
        DomItem *item = new DomItem(*(new QDomNode()), row, this);   // this doesn't seem to be correct...
        childItems.insert(position, item);
    }

    return true;
}

来源:https://stackoverflow.com/questions/9502432/qt4-making-simple-dom-model-editable-inserting-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!