Important: Please read the Qt Code of Conduct -

QSet with a Custom Class

  • I was looking for a very simple example of a Custom Class being used in a QSet, and I could not find one anywhere.

    I have eventually worked out this example, and I wanted to share with everyone, and also get feedback in case I did something wrong.


    #ifndef MYCLASS_H
    #define MYCLASS_H
    #include <QObject>
    #include <QDebug>
    class MyClass
        MyClass(const MyClass &other);
        MyClass &operator=(const MyClass &other);
        bool operator==(const MyClass &other) const;
        QString alpha;
        QString beta;
    inline uint qHash(const MyClass &key, uint seed){
        return qHash(key.alpha, seed) ^ qHash(key.beta, seed+1);
    QDebug operator<<(QDebug dbg, const MyClass &data);
    #endif // MYCLASS_H


    #include "myclass.h"
    MyClass::MyClass(const MyClass &other){
        alpha = other.alpha;
        beta = other.beta;
    MyClass& MyClass::operator=(const MyClass &other){
        MyClass *ret = new MyClass();
        ret->alpha = other.alpha;
        ret->beta = other.beta;
        return *ret;
    bool MyClass::operator==(const MyClass &other) const{
        return == 0 && == 0;
    QDebug operator<<(QDebug dbg, const MyClass &data){
        dbg.nospace() << "MyClass(" << data.alpha << ", " << data.beta << ")";
        return dbg.maybeSpace();


    #include <QCoreApplication>
    #include <QTimer>
    #include <QDebug>
    #include "myclass.h"
    int main(int argc, char *argv[]){
        QCoreApplication app(argc, argv);
        MyClass a;
        MyClass b;
        a.alpha = QString("Hello");
        a.beta = QString("World");
        b.alpha = QString("foo");
        b.beta = QString("bar");
        QSet<MyClass> set;
        qDebug() << set;
        QTimer::singleShot(250, &app, &QCoreApplication::quit);
        return app.exec();

    output looks like this:

    QSet(MyClass("foo", "bar"), MyClass("Hello", "World"))
    Press <RETURN> to close this window...

  • Qt Champions 2017

    Thanks sharing this example. We appreciate your effort. It helps others as well. Enjoy Qt Programming.

Log in to reply