Qt 使用自定义的数据类型作为QMap的Key(Class)

由于项目需要,有大量数据需要存入QMap中进行调用,而每个存入的数据包含:方位角度、距离、高度

因此我自定义数据类型PointData,为了让自定义数据能放入QVariant中,因此对自定义的数据类型PointData使用宏Q_DECLARE_METATYPE

QMap<key,value>中数据存入时会对存入数据进行比较,并按照比较后的顺序进行排序存储,因此需要重载运算<

为方便调试输入调试信息,我同时重载了运算符<<,输入QDebug信息。

先看PointData数据类型:

PointData.h

#ifndef POINTDATA_H
#define POINTDATA_H
#include <QMetaType>
#include <QDebug>
class PointData
{
public:
    PointData();
    PointData(const PointData& other);
    ~PointData();
    PointData(const int &azimuth, const int &distance,const int& height);

    int azimuth() const;
    int distance() const;
    int height() const;

    int Azimuth;
    int Distance;
    int Height;


private:
};

Q_DECLARE_METATYPE(PointData);
//! [custom type meta-type declaration]

//! [custom type streaming operator]
QDebug operator<<(QDebug dbg, const PointData &pointdata);

inline bool operator<(const PointData &p1,const PointData &p2){
    if(p1.Azimuth!=p2.Azimuth){
        return p1.Azimuth<p2.Azimuth;
    }
    else if (p1.Distance != p2.Distance) {
        return p1.Distance<p2.Distance;
    }else{
        return p1.Height<p2.Height;
    }
}

#endif // POINTDATA_H

排序方式优先级为:方位>距离>高度

PointData.cpp

#include "pointdata.h"

PointData::PointData(){

}

PointData::PointData(const PointData& other){
    Azimuth = other.Azimuth;
    Distance = other.Distance;
    Height = other.Height;
}

PointData::PointData(const int &azimuth, const int &distance,const int& height){
    Azimuth = azimuth;
    Distance = distance;
    Height = height;
}

PointData::~PointData(){

}


QDebug operator<<(QDebug dbg, const PointData &pointdata){
    dbg.space()<<"Azimuth:"<<pointdata.azimuth()<<"Distance:"<<pointdata.distance()<<"Height:"<<pointdata.height();
    return dbg.maybeSpace();
}

int PointData::azimuth() const{
    return Azimuth;
}

int PointData::distance() const{
    return Distance;
}

int PointData::height() const{
    return Height;
}

此时PointData可直接当做QVariant一般作为QMap的Key键值。使用方法举例:

    PointData p;
    p.Azimuth = 180;//方位值
    p.Distance = 300;//距离值
    p.Height = heightLevel;//高度值

    QMap<PointData,int>map;
    map[p]=10;
发布了6 篇原创文章 · 获赞 8 · 访问量 1126

猜你喜欢

转载自blog.csdn.net/zjgo007/article/details/104702360
今日推荐