Is there a way to allow QTableView
sections (columns) to be reordered (aka setSectionsMovable(true)
) but disallow any of the columns from being moved to index 0? I'd like to make it so that columns can be reordered by dragging them, but NOT allow the dragged column to be placed at the very beginning of the table.
Something like "if dragged column destination index equals 0, upon mouse release, cancel the drag and do nothing." Is this possible?
You can use the sectionMoved
signal and reverse the change.
#include <QApplication>
#include <QStandardItemModel>
#include <QTableView>
#include <QHeaderView>
class CustomHeaderView: public QHeaderView{
public:
CustomHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr)
: QHeaderView(orientation, parent)
{
connect(this, &CustomHeaderView::sectionMoved, this, &CustomHeaderView::onSectionMoved);
}
private slots:
void onSectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex){
Q_UNUSED(logicalIndex)
if(newVisualIndex == 0){
moveSection(newVisualIndex, oldVisualIndex);
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView w;
CustomHeaderView *headerview = new CustomHeaderView(Qt::Horizontal, &w);
w.setHorizontalHeader(headerview);
w.horizontalHeader()->setSectionsMovable(true);
QStandardItemModel model(10, 10);
for(int i = 0; i < model.columnCount(); ++i)
for(int j = 0; j < model.rowCount(); ++j)
model.setItem(i, j, new QStandardItem(QString("%1-%2").arg(i).arg(j)));
w.setModel(&model);
w.show();
return a.exec();
}