Qt TableView 模型 setData() 使应用程序崩溃

Qt TableView model setData() crashes application

我正在学习Qt,现在正在开发类似扫雷的游戏。

为了显示游戏板,我将 QTableView 与扩展 QAbstractTableModel.

的自定义模型一起使用

显示模型中的数据效果很好。我超载了 QVariant data(const QModelIndex &index, int role),所有单元格都正确显示了它们的 "content"。

现在我想处理游戏板点击并将任何数据传递给模型。

我重载了 setData() 函数:

bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role) {
    qDebug("setData invoked");
    return false;
}

并处理了 TableView 点击:

MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QTableView *tableView = this->findChild<QTableView*>("tableView");
    tableView->setModel(new MyModel(tableView, DEFAULT_ROWS_NUM, DEFAULT_COLS_NUM));

    QObject::connect(tableView, &QAbstractItemView::clicked, [&](const QModelIndex &index) {
        qDebug(qUtf8Printable(QString("click: %1 %2").arg(index.row()).arg(index.column())));
        tableView->model()->setData(index, 'W'); // this line crashes application
    });
}

tableView->model()->setData() 导致应用程序崩溃:

Crashed Thread:        0  Dispatch queue: com.apple.main-thread
Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000008
Exception Note:        EXC_CORPSE_NOTIFY

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   org.qt-project.QtWidgets        0x0000000104bc9c67 QAbstractItemView::model() const + 7
1   studia.Minesweeper              0x0000000104939501 MainWindow::MainWindow(QWidget*)::$_0::operator()(QModelIndex const&) const + 385 (mainwindow.cpp:13)

我是不是做错了什么?这是实现鼠标点击事件模型变化的好方法吗?

你的闭包有问题[&]。将其替换为 [tableView].