qtqtableview

Move a table column to beginning first column index on the table


Using Qt 5.2.1, I have a QTableView in which I have enabled sorting of columns by the user, i.e., they can drag and drop columns by the headers to rearrange them.

I want to add a right-click option "Move to front", where the user can right-click a column header, and when the option is clicked, that column will be moved to the leftmost spot on the table (first column index).

I have it set up where it gets to my function properly, but I cannot figure out how to make it move the column once it gets to that point. The rearranging works fine with the drag and drop, but I'm not sure how to have it go automatically to a given index.


Solution

  • void SomeClass::moveColumnToFront(int column, QTableView *table) {
        // I assume that you are using QStandardItemModel
        QStandardItemModel *model = qobject_cast<QStandardItemModel *>(table->model());
        if (model) {
             QList<QStandardItem *> columndData = model->takeColumn(column);
             model->insertColumn(0, columndData);
        }
    }
    


    You should learn to search documentation! Yes it is possible to do it using QAbstractItemModel API. But remember that model have to support this feature (QStandardItemModel does)! If you are you using some custom model this may not work.

    void SomeClass::moveColumnToFront(int column, QTableView *table) {
        bool success = table->model()->moveColumn(QModelIndex(), column, 
                                                  QModelIndex(), 0);
    }