上一篇文章負責把設計好的控件數據導出到了xml文件,本偏文章負責把導出的xml數據文件導入,而後在畫布上自動生成對應的控件,Qt內置的xml數據解析功能,很是強大,都封裝在QtXml組件中,Qt有個好處就是,封裝了衆多的各大操做系統平臺的功能,尤爲是GUI控件,不愧是超大型一站式GUI超市,雖然網絡組件不是很強大,可是應付一些基礎應用仍是綽綽有餘的。在導出xml數據的時候,屬性列表和值都按照xml的屬性存儲的而不是子節點,因此在解析的時候須要遍歷節點的屬性名稱和屬性值,QDomNamedNodeMap attrs = element.attributes();而後循環挨個取出名稱和值便可,QDomNode n = attrs.item(i);QString nodeName = n.nodeName();QString nodeValue = n.nodeValue();node
體驗地址:https://pan.baidu.com/s/1A5Gd77kExm8Co5ckT51vvQ 提取碼:877p 文件:可執行文件.ziplinux
void frmMain::openFile(const QString &fileName) { //打開文件 QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { return; } //將文件填充到dom容器 QDomDocument doc; if (!doc.setContent(&file)) { file.close(); return; } file.close(); //先清空原有控件 QList<QWidget *> widgets = ui->centralwidget->findChildren<QWidget *>(); qDeleteAll(widgets); widgets.clear(); //先判斷根元素是否正確 QDomElement docElem = doc.documentElement(); if (docElem.tagName() == "canvas") { QDomNode node = docElem.firstChild(); QDomElement element = node.toElement(); while(!node.isNull()) { QString name = element.tagName(); //存儲座標+寬高 int x, y, width, height; //存儲其餘自定義控件屬性 QList<QPair<QString, QVariant> > propertys; //節點名稱不爲空才繼續 if (!name.isEmpty()) { //遍歷節點的屬性名稱和屬性值 QDomNamedNodeMap attrs = element.attributes(); for (int i = 0; i < attrs.count(); i++) { QDomNode n = attrs.item(i); QString nodeName = n.nodeName(); QString nodeValue = n.nodeValue(); //qDebug() << nodeName << nodeValue; //優先取出座標+寬高屬性,這幾個屬性不能經過setProperty實現 if (nodeName == "x") { x = nodeValue.toInt(); } else if (nodeName == "y") { y = nodeValue.toInt(); } else if (nodeName == "width") { width = nodeValue.toInt(); } else if (nodeName == "height") { height = nodeValue.toInt(); } else { propertys.append(qMakePair(nodeName, QVariant(nodeValue))); } } } //qDebug() << name << x << y << width << height; //根據不一樣的控件類型實例化控件 int count = listWidgets.count(); for (int i = 0; i < count; i++) { QString className = listWidgets.at(i)->name(); if (name == className) { QWidget *widget = listWidgets.at(i)->createWidget(ui->centralwidget); //逐個設置自定義控件的屬性 int count = propertys.count(); for (int i = 0; i < count; i++) { QPair<QString, QVariant> property = propertys.at(i); widget->setProperty(property.first.toLatin1().constData(), property.second); } //設置座標+寬高 widget->setGeometry(x, y, width, height); //實例化選中窗體跟隨控件一塊兒 newSelect(widget); break; } } //移動到下一個節點 node = node.nextSibling(); element = node.toElement(); } } }