How to get the row of an item in QSortFilterProxyModel giving QString?

1.4k views Asked by At

I'm pretty new using QSortFilterProxyModel and I kind a lost. I'm implementing a "TcpSocket" register, so every time a client is connected to a server, I get a sorted model in QML, which shows the ip of each client. The problem is each time the QSortFilterProxyModel is refreshed due to a new/lost connection the variable isCurrentItem lose all its sense because the list is updated but not the index of the list. Then, what I want to do is create a function in the QSortFilterProxyModel implementation which return its "position" given the ip of the client to update correctly the current item index.

For your reference, I found this code which does exactly the contrary of what I want to do (return the "ip" of the client of the client registered on a certain "row):

QVariantMap proxyModel::getIP(int row) {
    QHash<int,QByteArray> names = roleNames();
    QHashIterator<int, QByteArray> i(names);
    QVariantMap res;
    while (i.hasNext()) {
        i.next();
        QModelIndex idx = index(row, 0);
        QVariant data = idx.data(i.key());
        res[i.value()] = data;
        qDebug() << i.key() << ": " << i.value() << " " << data;
    }
    return res;
}

Note that it simulates the ListModel::get(int row) of a normal QML model. Has everyone any hint to achieve my purpose?

1

There are 1 answers

0
albertTaberner On BEST ANSWER

Ok, that's what I do to get the row:

int proxyModel::getIp(QString ip)
{
    QHash<int,QByteArray> names = roleNames();
    QHashIterator<int, QByteArray> i(names);
    while (i.hasNext()){
        i.next();
        int proxylenght = rowCount();
        for(int a=0;a<proxylenght;a++)
        {
            QModelIndex idx = index(a, 0);
            QVariant data = idx.data(i.key());
            if(data == ip)
               return a;
        }
    }
    return -1;
}

Anyway, I am not sure this is the most effecincy way to handle it.