Qt QTableView 拖放:将选择拖动到表格周围的区域会导致程序崩溃

问题描述

我使用 QTableView 和拖放创建了一个最小的 QAbstractTableModel 示例。

它工作正常,只是将选择拖动到表格周围的区域会导致程序崩溃:

enter image description here

知道为什么会这样吗?

我在下面列出了 QAbstractTableModel 的实现。 full project is at GitHub

#include "mainwindow.h"

#include <QAbstractTableModel>
#include <qabstractitemmodel.h>
#include "tablemodel.h"

using std::vector;


QModelIndex TableModel::index(int row,int column,const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return createIndex(row,column);
}

QModelIndex TableModel::parent(const QModelIndex &child) const {
    Q_UNUSED(child);
    return QModelIndex();
}

QVariant TableModel::data(const QModelIndex &index,int role) const {
    if (role == Qt::displayRole)
        return dataList[index.row()][index.column()];
    return QVariant();
}

bool TableModel::setData(const QModelIndex &index,const QVariant &value,int role) {
    Q_UNUSED(role);
    dataList[index.row()][index.column()] = value;
    emit dataChanged(index,index);
    return true;
}

int TableModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return dataList.size();
}

int TableModel::columnCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return 3;
}

Qt::ItemFlags TableModel::flags(const QModelIndex &index) const {
    Q_UNUSED(index);
    return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
}

Qt::DropActions TableModel::supportedDropActions() const {
    return Qt::copyAction | Qt::MoveAction;
}

bool TableModel::insertRows(int row,int count,const QModelIndex &parent) {
    if (count > 0) {
        beginInsertRows(parent,row,row + count + 1);
        for (int i = 0; i != count; i++)
            dataList.emplace(dataList.begin() + row,columnCount());
        endInsertRows();
        emit dataChanged(index(row,0),index(row + count - 1,columnCount()));
        emit layoutChanged();
        return true;
    }
    else {
        return false;
    }
}

bool TableModel::removeRows(int row,const QModelIndex &parent) {
    if (count > 0) {
        beginRemoveRows(parent,row + count + 1);
        dataList.erase(dataList.begin() + row,dataList.begin() + row + count);
        endRemoveRows();
        emit dataChanged(index(row,columnCount()));
        emit layoutChanged();
        return true;
    }
    else {
        return false;
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)