Important: Please read the Qt Code of Conduct -

How can i sort an alphanumeric string in abstract table view

  • Hi, am new to QT. I am using a QAbstractTableModel for displaying some file information. One of the column contains size of the file. If the size is maintained as double[without any unit like Kb, Mb, Gb] then sorting works fine with the following code

    class MyModel : public QAbstractTableModel   
    QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel( myModel );
    ui->tableView->setModel( proxyModel );

    But when i try to maintain the file size in human readable format[with units Kb, Mb, Gb] then i changed double to QString and then sorting is not in proper order. I know that sorting of strings work based on ASCII values but how can i achieve proper sorting for this case?

    PS: I tried implementing lessthan function on my own, but faced ambiguity error because of QAbstractTableModel and QSortFilterProxyModel

  • Moderators

    Hi, welcome to the forum.

    No need to implement string sorting. It will be slow and is unnecessary. This is a good use case for user roles in a model.
    Make the model return a decorated string value for Qt::DisplayRole and the original double value for some custom role (e.g. Qt::UserRole). Then set the sorting role in the proxy model like this: proxyModel->setSortRole(Qt::UserRole); and you should be good to go. Displayed will be the string but for sorting the original double value will be used.

    Btw. surround code with ``` to make it format better (I corrected your post).

  • Thank you Chris...It works :)

Log in to reply