有没有一种方法可以允许对索引部分(列)进行重新排序(又称setSectionsMovable(true)
),但不允许将任何列移动到索引0?我想让列可以通过拖拽来重新排序,但不允许将拖拽的列放在表的最开始。
类似于“如果拖动的列目标索引等于0,则在释放鼠标时,取消拖动并不执行任何操作”之类的语句。这个是可能的吗?
发布于 2018-07-08 14:32:49
您可以使用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();
}
https://stackoverflow.com/questions/51229311
复制相似问题