Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Why does not QListWidget sort correctly?



  • Hi everybody,

    Could somebody give me some help?
    I want to use QListWidget sortItems() function. I enabled sortingEnable. But I don't think the result is correct.
    If I input items 1, 2, 1152, the result will be 1, 1152, 2. But I think the result should be 1, 2, 1152.

    And if I test this code,
    if("1" == "1152")
    {
    qDebug() << "'1' == '1152'";
    }
    else if("1" > "1152")
    {
    qDebug() << "'1' > '1152'";
    }
    else
    {
    qDebug() << "'1' < '1152'";
    }
    if("2" == "1152")
    {
    qDebug() << "'2' == '1152'";
    }
    else if("2" > "1152")
    {
    qDebug() << "'2' > '1152'";
    }
    else
    {
    qDebug() << "'2' < '1152'";
    }
    The output is
    '1' < '1152'
    '2' < '1152'

    I think this is right.

    So could somebody give me some advice?
    Thanks in advance.



  • Do you know that you are comparing their memory addresses?
    If you want to test the comparing, you should write like this

    if(QString("1") == QString("1152"))
    

    And the result is

    '1' < '1152'
    '2' > '1152'
    

    That is how string comparision works.
    It will not compare the number value...

    One workaround to this is that do not use setText, but

    item->setData(Qt::DisplayRole, 1151);
    


  • @Bonnie Thank you very much.
    You explained how string comparision works. That is correct. And I tested as you said. But in my opinion, I still think they should compare the length of each string. Let it alone.

    At first my code is
    ui->listWidget->addItem(QString::number(nNum));
    ui->listWidget->sortItems();
    It works. I can see the num in the listwidget.

    But after I changed the code to
    QListWidgetItem item;
    item.setData(Qt::DisplayRole, nNum);
    ui->listWidget->addItem(&item);
    ui->listWidget->sortItems();
    It doesn'tt work. I can't see anything.



  • @Qingshui-Kong said in Why does not QListWidget sort correctly?:

    But after I changed the code to
    QListWidgetItem item;
    item.setData(Qt::DisplayRole, nNum);
    ui->listWidget->addItem(&item);
    ui->listWidget->sortItems();

    You were very close to the solution, you just have to create the QListWidgetItem on the heap instead of the stack otherwise it gets destroyed:

    auto item = new QListWidgetItem;
    item->setData(Qt::DisplayRole, nNum);
    ui->listWidget->addItem(item);
    ui->listWidget->sortItems();
    


  • @Qingshui-Kong said in Why does not QListWidget sort correctly?:

    But in my opinion, I still think they should compare the length of each string.

    Then you had better let the C++/Qt designers know you don't agree with the way string comparisons work.



  • @VRonin Thanks. After I responded. I tried that. It worked.



  • @JonB Maybe I just made a mistake. I just think I saw something like that.


Log in to reply