1

有没有办法允许对QTableView部分(列)进行重新排序(又名setSectionsMovable(true))但不允许将任何列移动到索引 0?我想这样做,以便可以通过拖动列来重新排序,但不允许将拖动的列放置在表格的最开头。

类似“如果拖动的列目标索引等于 0,则在释放鼠标时,取消拖动并且什么也不做”之类的东西。这可能吗?

4

1 回答 1

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();
}
于 2018-07-08T06:32:49.257 回答