Important: Please read the Qt Code of Conduct -

How to update displayed row number after dragdrop in QTableView

  • Hello,
    I successfully enabled the ability to move rows within a QTableView. I also have the row numbers display (In the row headers) enabled. The following are my settings:

    Let's say I start out with rows (row contents in braces): 
    Row #1 -> (A), Row #2  -> (B), Row #3 -> (C).
    I grab and move row 1, to after row 3.
    The view now shows the following:
    Row #2  -> (B), Row #3 -> (C), Row #1 -> (A),
    How can I update and reassign the row numbers in the view?  After the item has been dropped I want it to show:
    Row #1 -> (B), Row #2  -> (C), Row #3 -> (A)

  • Lifetime Qt Champion


    What model do you have underneath ?

    In any case, you likely want to re-implement the model's headerData method.

  • I have my own implementation of the model. It is subclassed off of QAbstractTableModel. I have already re-implemented the headerData method.

    In the headerData method, I currently have the following code to display the row numbers:

        if(orientation == Qt::Vertical)
            return QString::number(section + 1);

    Can you please give me a hint on what I need to do in the headerData method?

  • Lifetime Qt Champion

    Ok... It's a bit more tricky than that as it seems.

    Use this custom QHeaderView class:

    class HeaderView : public QHeaderView
        HeaderView(Qt::Orientation orientation, QWidget *parent = nullptr)
        : QHeaderView(orientation, parent)
    void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override
        QHeaderView::paintSection(painter, rect, visualIndex(logicalIndex));

  • SGaist,
    You are truly amazing. I was able to get it to work with this.

    One last tip request: After the drop has finished I want to take the moved row, access it's details and do further processing. How can I accomplish this?


  • Lifetime Qt Champion

    You can re-implement dropMimeData and launch the processing from there.

Log in to reply