上一篇文章负责把设计好的控件数据导出到了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(); } } }