Convert XML file to QAbstractItemModel

493 views Asked by At

I would like to build an auto completer for a QtWidget (QPlainTextEdit). The key words I want to use are stored in an XML file. Is there an easy way to get the XML file into the QCompleter? The QCompleter can be called with a QAbstractItemModel or a QStringList. So I hoped there is a function that will turn my XML file into one of these two things. Is this possible or do I have to read my XML file line by line and fill a model or a list?

Thanks for any hints.

1

There are 1 answers

1
Daniel Vrátil On BEST ANSWER

There's no automatic conversion from XML to a list, mostly because the XML can have an arbitrary structure. There is QXmlStreamReader class that you can use to parse the XML and populate the model.

Assuming the XML looks something like

<keywords>
  <keyword>Foo</keyword>
  <keyword>Bar</keyword>
</keywords>

Then you only need a couple of lines to parse it:

QXmlStreamReader reader(xmlFileName);
QStringList keywords;
while (!reader.atEnd()) {
    // parse next token
    reader.readNext();
    // is this an opening "keyword" tag?
    if (reader.isStartElement() && reader.name() == QLatin1String("keyword")) {
        // add its value to the list
        keywords.append(reader.text().toString());
    }
}

auto completer = new QCompleter(keywords, lineEdit);
...

You might want to use the model ctor (e.g. with QStringListModel) if you want to populate the completer with data from a different XML file for example based on some configuration, since you can then easily clear() and re-populate the model again. You can also share the same model between multiple QCompleter instances.