How to use Qt::CaseInsensitive in Qtablewidget data sorting?



  • i am using QTablewidget. i want to sort one of the column in QTableWidget. Column data have CaseInsensitive(upper and lower). when I do setSortingEnabled() true it only sorts it in alphabetic order for Uppercase.

    Miss out the small letter alphabetic data. i want sort the Column data from both (upper and lower) alphabetic order. If any sample code or url pls?

    How to apply Qt::CaseInsensitive in Qtablewidget sorting?



  • On my machine sorting in QTableWidget is case insensitive by default, so I assume you want a case sensitive sort: that is words starting with A-Z sort before words starting a-z.

    Make a subclass of QTableWidgetitem and override the default operator<() to do a case-sensitive comparison. Use that subclass for the items you add to the table.

    Here is a complete program. The left column sorts one way, the right column the default.
    @#include <QtGui>
    #include <QDebug>

    class MyItem: public QTableWidgetItem
    {
    public:
    MyItem(const QString &text, int type = Type):
    QTableWidgetItem(text, type)
    { }

    bool operator< ( const QTableWidgetItem & other ) const {
        return (QString::compare(
                data(Qt::DisplayRole).toString(),
                other.data(Qt::DisplayRole).toString(), Qt::CaseSensitive ) < 0 );
    }
    

    };

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);
    QStringList values;
    values << "Z" << "b" << "B" << "a" << "A";
    QTableWidget tw(5,2);
    for (int r = 0; r < 5; ++r) {
    tw.setItem(r, 0, new MyItem(values.at(r))); // left column uses our sorting
    tw.setItem(r, 1, new QTableWidgetItem(values.at(r))); // right column uses default
    }
    tw.setSortingEnabled(true);
    tw.show();
    return app.exec();
    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.