菜单是一种具有层次结构的控件,其子项同样适合用xml文件存储。
以下是我写的一个类XmlMenuBar,从QMenuBar和ReadWriteXml两个类中派生。
**注意:**由于ReadWriteXml中引用了读写xml的第三方类,文件较多,单独进行了上传,见读写xml的c++类
#ifndef XMLMENUBAR_H
#define XMLMENUBAR_H
#include <QMenuBar>
#include"./tinyxml/readwritexml.h"
class XmlMenuBar : public QMenuBar,public ReadWriteXml
{
Q_OBJECT
public:
explicit XmlMenuBar(QWidget *parent = nullptr);
QAction* actionByName(const QString &name);
protected:
void readXmlRootElement(const TiXmlElement* rootElement);
void writeXmlRootElement(TiXmlElement* rootElement);
private:
signals:
};
#endif // XMLMENUBAR_H
#include "xmlmenubar.h"
#include<QDebug>
XmlMenuBar::XmlMenuBar(QWidget *parent)
: QMenuBar(parent)
{
}
void XmlMenuBar::readXmlRootElement(const TiXmlElement *rootElement)
{
//找第一个
const TiXmlElement* element=rootElement->FirstChildElement("Control");
while (element)
{
const char* menuName=element->Attribute("Name");
if(menuName) //创建菜单
{
QMenu* menu=addMenu(menuName);
//下拉菜单项
const TiXmlElement* elementItem=element->FirstChildElement("Control");
while (elementItem)
{
const char* actionName=elementItem->Attribute("Name");
if(actionName)
{
const char* objName=elementItem->Attribute("Object");
QAction *action=menu->addAction(actionName);
action->setObjectName(objName);
}
//继续读下一个
elementItem=elementItem->NextSiblingElement("Control");
}
}
//继续读下一个
element=element->NextSiblingElement("Control");
}
}
void XmlMenuBar::writeXmlRootElement(TiXmlElement *rootElement)
{
qDebug()<<rootElement->Attribute("name");
}
QAction *XmlMenuBar::actionByName(const QString &name)
{
return findChild<QAction*>(name);
}