禁止将列移到索引0?

时间:2018-07-08 06:06:24

标签: c++ qt qt5 qtableview qheaderview

是否有一种方法可以允许对QTableView节(列)进行重新排序(又名setSectionsMovable(true)),但不允许任何列移动到索引0?我想这样做,以便可以通过拖动对列进行重新排序,但不允许将被拖动的列放在表格的最开始。

类似于“如果拖动的列的目标索引等于0,则在释放鼠标时取消拖动并且不执行任何操作”。这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用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();
}