禁止列移动到索引 0?

Disallow column from getting moved to index 0?

有没有办法允许 QTableView 节(列)重新排序(又名 setSectionsMovable(true))但不允许将任何列移动到索引 0?我想这样做,以便可以通过拖动来重新排序列,但不允许将拖动的列放在 table.

的最开头

类似"if dragged column destination index equals 0, upon mouse release, cancel the drag and do nothing."这可能吗?

您可以使用 sectionMoved 信号并撤消更改。

#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();
}