Solved how to load and save the combobox values in XML
-
I have done the code by using QSettings apart from this i want to load and save the combobox by using XML i tried a lot but i dnt find any result
thanks in advance.
-
Did you check out Qt's XML examples?
-
yes @koahnig i am cleared in the example but cant implemnt in my code
-
Well, my personal opinion is that you will have a lot of overhead there. However, that is the XML functionality provided by Qt.
You may want to explain why you got stuck. Possibly someone can help.
-
You can use the "Model Serialisation" module of this library to save and load the
QCombobox::model
. After you have done that you'll just need to prepend an element containing the current index:#include <QApplication> #include <QPushButton> #include <QLabel> #include <QComboBox> #include <QXmlStreamWriter> #include <QXmlStreamReader> #include <XmlModelSerialiser> #include <QVBoxLayout> #include <QDebug> QString saveCombo(const QComboBox* combo){ XmlModelSerialiser modelSerialiser(combo->model()); modelSerialiser.setPrintStartDocument(false); QString result; QXmlStreamWriter writer(&result); writer.writeStartElement("combobox"); writer.writeStartElement("currentIndex"); writer.writeCharacters(QString::number(combo->currentIndex())); writer.writeEndElement(); //currentIndex writer.writeStartElement("comboModel"); modelSerialiser.saveModel(writer); writer.writeEndElement(); //comboModel writer.writeEndElement(); //combobox return result; } void loadCombo(QComboBox* combo, const QString& data){ QXmlStreamReader reader(data); int currIdx = -1; XmlModelSerialiser modelSerialiser(combo->model()); QString modelData; while (!reader.atEnd() && !reader.error()) { switch(reader.readNext()){ case QXmlStreamReader::StartElement: if(reader.name()=="currentIndex") currIdx = reader.readElementText().toInt(); else if(reader.name()=="comboModel"){ reader.readNextStartElement(); modelSerialiser.loadModel(reader); } break; default: break; } } if(reader.error()) qDebug() << reader.errorString(); combo->setCurrentIndex(currIdx); } int main(int argc, char **argv) { QApplication app(argc, argv); QWidget mainWid; QVBoxLayout *mainlay = new QVBoxLayout(&mainWid); mainlay->addWidget(new QLabel("Save This",&mainWid)); QComboBox* example = new QComboBox(&mainWid); example->addItem("a"); example->addItem("b"); example->addItem("c"); mainlay->addWidget(example); mainlay->addWidget(new QLabel("Load This",&mainWid)); QComboBox* loadedCombo = new QComboBox(&mainWid); mainlay->addWidget(loadedCombo); QPushButton* testButton = new QPushButton("Test",&mainWid); QObject::connect(testButton,&QPushButton::clicked,[example,loadedCombo](){ const QString savedCombo = saveCombo(example); qDebug() << savedCombo; loadCombo(loadedCombo,savedCombo); }); mainlay->addWidget(testButton); mainWid.show(); return app.exec(); }
-
thanks a lot @VRonin