[Qt-interest] Problem with qSort and QObjects

Carl Snellman carl.snellman at gmail.com
Tue Feb 16 19:11:33 CET 2010


Yeah, you're right, I though I could not do it as I could not get a
test version working first, but the problem was actually elsewhere...
growth pains I guess.

Here's the test code I got working (just in case it would be useful
for someone else):

main.cpp:
>>>>>>>>>>>>>>>>>>>>>
#include <QtCore/QCoreApplication>
#include <QDebug>
#include "account.h"

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);
    QList<Account *> list;
    list.append(new Account("item 5", "Dummy"));
    list.append(new Account("item 1", "Dummy"));
    list.append(new Account("item 3", "Dummy"));
    list.append(new Account("item 4", "Dummy"));
    list.append(new Account("item 2", "Dummy"));

    for (int i=0; i<5; ++i)
        qDebug() << list[i]->toString();

    qSort(list.begin(), list.end(), compareObjects);

    for (int i=0; i<5; ++i)
        qDebug() << list[i]->toString();
    return 0;
}
<<<<<<<<<<<<<<<<

account.h
>>>>>>>>>>>>>>>>
#ifndef ACCOUNT_H
#define ACCOUNT_H

#include <QObject>
#include <QDebug>

class Account : QObject {
    Q_OBJECT
public:
    Account() {};
    Account(QString aItem, QString bItem)
             : aItem(aItem), bItem(bItem) {};
    QString aItem;
    QString bItem;
    QString toString(){
        QString result;
        return result.append("aItem = ").append(aItem).append("\t")
                .append("bItem = ").append(bItem).append("\n");
    };
};

bool compareObjects(const Account * a1, const Account * a2);
#endif // ACCOUNT_H
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


account.cpp
>>>>>>>>>>>>>>>>>>>>>>>>>>>
#include "account.h"

bool compareObjects(const Account * a1, const Account * a2) {
    qDebug() << "compareObjects: " << a1->aItem << ":" << a2->aItem;
    return a1->aItem < a2->aItem;
}
<<<<<<<<<<<<<<<<<<<<<<<<


Thanks everyone!

Carl


On Tue, Feb 16, 2010 at 1:40 PM, Florian Vichot
<florian.vichot at diateam.net> wrote:
>> Yeah, the code I added to email was a simple case to showcase the
>> problem. My actual code uses signals...
>> To get my actual stuff working, I had to remove QObject inheritance
>> and thus the signals, which was unfortunate...
>
> Why remove the QObject inheritance ? simply store pointers to QObject
> instead of QObject per value, and use the three arguments form of qSort
> (see previous email), and provide your own compare function...
>
> Florian
>
>
>



More information about the Qt-interest-old mailing list