Important: Please read the Qt Code of Conduct -

Custom object type and QList

  • Guys give some hint about operator overloading

    I have such QList: QList<MyCustomType*> list;
    What kind of operator==() , must have my custom type, to have ability use it in method QList::indexOf(MyCustomType*)


  • Moderators

    That should just work (as long as you are using pointers) without operator overloading.

  • Indeed. Nothing needed. You are putting in pointers, and pointers already have the operators you need by default. Note that no comparisons will be made on the contents of the objects. It is purely a comparison of the pointer values.

  • ))) Just forgot to check if list is filled out. A on more question

    QList<MyCustomType> list;

    Is memory released, as objects goes out of scope ?

  • Yes. However, you cannot do that with QObject derived types, as the types you put in your container must be copyable and default constructable. QObject does not meet those requirements. You can put pointer to a QObject in your container, but no delete will be called automatically on those pointers on destruction of the list object. That means that if that was the only pointer to object, you are leaking memory.

    A last alternative is to store shared pointers in your list. [[doc:QSharedPointer]] fulfils the requirements of types to put in a container, and when the list is destructed, they will automatically delete anything they pointed to if there are no other shared pointers pointing to the same data.

  • Thx, but if containers contains of such clasess

    @class MyClass : public QObject

    QList<MyClass> list;


    Edit: please use @ tags around code sections; Andre

  • That won't compile. Line 6 will probably throw some rather complicated template-related error messages.

  • Thx, big thx for advise))) !!!

Log in to reply