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

tableWidget does not sort itself



  • Hi All,
    I have a tablewidget, and I cannot get it to sort on the first column. What am I missing?
    Cheers,
    Cedric

    //constructor:
    const int IDXSTART = 0;
    tableWidget = new QTableWidget(0,9,this);
    tableWidget->setHorizontalHeaderLabels(HORHEADERS.split(";"));
    QVBoxLayout *centralLayout = new QVBoxLayout;
    centralLayout->addWidget(tableWidget);
    //add rows to the table
    tableWidget->insertRow(row);
    tableWidget->setCellWidget(row,IDXSTART,new QDateTimeEdit);
    ((QDateTimeEdit*)(tableWidget->cellWidget(row,IDXSTART)))->setDisplayFormat(DTFORMAT);
    qint64 starttime = dateTimeEdit->dateTime().toMSecsSinceEpoch();
    ((QDateTimeEdit*)(tableWidget->cellWidget(row,IDXSTART)))->setDateTime(datetime.fromMSecsSinceEpoch(starttime));
    //sort rows
    void MainWindow::sortRows(void)
    { //sort the lines on date / time in the list.
        tableWidget->setSortingEnabled(TRUE);
        tableWidget->sortByColumn(0,Qt::AscendingOrder);
        //tableWidget->sortItems(IDXSTART); //this does not sort the table
        tableWidget->setSortingEnabled(FALSE);
    }
    

  • Lifetime Qt Champion

    Hi,

    AFAIK, the sorting happens on the content of a cell. You don't have anything in your cells, only the widgets set.

    Rather than putting a QDateTimeEdit on each cell, you can create your own QStyleItemDelegate that handles the date the way you want it. That would also be better performance wise.



  • Hi SGaist,
    Thanks for the fast reply. Before I dive into this, do you know if there's an example I can study?
    Cheers,
    Cedric


  • Lifetime Qt Champion

    Do you mean example of custom QStyledItemDelegate ?



  • @SGaist
    Hi SGaist,
    An example of QStyledItemDelegate would be nice.
    Cheers,
    Cedric


  • Lifetime Qt Champion

    There's one linked in the documentation of QStyledItemDelegate.


Log in to reply