xmlqtdomqtreeviewqtxml

Qt QTreeView editable DOM model


I have a QTreeView to which I set a subclassed DomModel:QAbstractItemModel. Each item is a DomItem which deals mostly with QDomNode. I set QDomDocument to this model. I think I've derived this system from one of the Qt examples.

It has 3 columns: 0 for node name, 1 for attributes and 2 for value.

Anyway, I wanted to make this XML DOM tree editable. I've modified some flags such as Qt::ItemIsEditable and some other things in the model class and now I can edit the model through QTreeView by double clicking.

For column 2 it's easy, since QDomItem has this setNodeValue function, however I've found there are no "set" functions for item->node().NodeName() and item->node().attributes() which would, I presume, modify columns 0 and 1.

So now when I modify column 2 it works, however columns 0 and 1 revert to their previous values upon pressing enter.

bool DomModel::setData(const QModelIndex &index, const QVariant &value,
                    int role)
{
if (role != Qt::EditRole) return false;

DomItem *item = static_cast<DomItem*>(index.internalPointer());

switch (index.column()){
    case 0:
        // ???
        break;
    case 1:
        // ???
        break;
    case 2:
        item->node().setNodeValue(value.toString());   // This works - QTreeView is updated
        break;
}
...
}

Solution

  • Well, apparently item->node().toElement() which returns a QDomElement has the necessary "set" functions and it works. So I think I've found a way to fully modify my XML DOM file through QTreeView.

    This does the trick for me:

    switch (index.column()){
       case 0: // added
          item->node().toElement().setTagName(value.toString());
          break;
       case 1: // added
          // this shall be modified to account for nonstandard spacings, etc.
          aux = value.toString().trimmed();
          aux.remove("\"");
          attributes.clear();
          attributes = aux.split(" ");
          for(int i = 0; i<attributes.size(); i++){
             item->node().toElement().setAttribute(attributes.at(i).split("=").at(0),
                                                   attributes.at(i).split("=").at(1));
          }
          break;
       case 2: // Left it as it is
          item->node().setNodeValue(value.toString());   // This works - QTreeView is updated
          break;
    }