之前的项目需求里面有实现鼠标拖拽对QTableWidget中的数据行进行拖拽排序的需求,因此撰文记录。有需要的同学请自取。

代码Gist

实现核心--实现dropEvent进行排序

代码中只需要分别处理下移到最后和移动到已有QTableWidget的行的逻辑即可实现

实现的核心代码:

void DragableTableWidget::dropEvent(QDropEvent *ev)
{
    qDebug() << "dropEvent";

    int rowSrc;
    int rowDst;
    int rowToRemove;
    int rowToFill;

    rowSrc = currentRow();
    rowToRemove = rowSrc;
    QTableWidgetItem *pItem = itemAt(ev->pos());
    if (pItem) {    // item exists, so move in the table
        rowDst = pItem->row();
        if (rowSrc == rowDst) {
            return;
        }

        rowToRemove = rowDst < rowSrc ? rowSrc + 1 : rowSrc;
        rowToFill = rowToRemove < rowDst ? rowDst + 1 : rowDst;

    } else {    // no item means, move to the end of the table
        rowDst = rowCount();
        rowToFill = rowDst;
    }

    qDebug() << "src" << rowSrc << "dst" << rowDst << "remove" << rowToRemove << "fill" << rowToFill;
    insertRow(rowToFill);    // insert Row
    const int _rowHeight = rowHeight(rowToRemove);
    setRowHeight(rowToFill, _rowHeight);   // copy the original row height

    // move the items to new row
    for (int col = 0; col < this->columnCount(); ++col) {
        setItem(rowToFill, col, takeItem(rowToRemove, col));
    }

    this->removeRow(rowToRemove); // remove the original row after inserting the new row.

}

演示效果

演示效果