开发环境:
QT 5.0.2 MinGW 32bit
这里主要讨论key为QString,value为结构体指针类型的QHash。例如:
QHash<QString, QUserInfo*> m_hash;
一:在工程中添加新类:
“添加新文件”-》“C++”->"C++类",生成文件quserinfo.h和quserinfo.cpp。
quserinfo.h:
#ifndef QUSERINFO_H
#define QUSERINFO_H
#include <QString>
class QUserInfo
{
public:
QUserInfo();
QString getName();
void setName(const QString sName);
private:
QString m_sName;
};
#endif // QUSERINFO_Hquserinfo.cpp:
#include "quserinfo.h"
QUserInfo::QUserInfo()
{
}
QString QUserInfo::getName()
{
return m_sName;
}
void QUserInfo::setName(const QString sName)
{
m_sName = sName;
}
二:在×××.h文件中
#include "quserinfo.h"并在类中添加:
QHash<QString, QUserInfo*> m_hash;
添加item:
for (int i = 0; i < 10; i++)
{
QString sName = QString("name%1").arg(i);
pUserInfo = new QUserInfo();
pUserInfo->setName(sName);
m_hash.insert(sName, pUserInfo);
}
遍历:
QHash<QString, QUserInfo*>::const_iterator i = m_hash.constBegin();
while (i != m_hash.constEnd())
{
qDebug() << i.key() << ": " << i.value() << endl;
++i;
}
一个个删除节点:
QHash<QString, QUserInfo*>::const_iterator j = m_hash.constBegin();
QHash<QString, QUserInfo*>::const_iterator delIndex = j;
while ((delIndex = j) != m_hash.constEnd())
{
qDebug() << delIndex.key();
QUserInfo* userInfo = (QUserInfo*)delIndex.value();
if (userInfo != NULL)
{
delete userInfo;
userInfo = NULL;
}
++j;
m_hash.remove(delIndex.key());
}
删除全部节点:
QHash<QString, QUserInfo*>::const_iterator j = m_hash.constBegin();
while (j != m_hash.constEnd())
{
qDebug() << j.key();
QUserInfo* userInfo = (QUserInfo*)j.value();
if (userInfo != NULL)
{
delete userInfo;
userInfo = NULL;
}
++j;
}
m_hash.clear();
注意:如果是new出来的哈希指针,在clear()之后最好delete一下。