Krzysiek
Krzysiek

Reputation: 8385

Qt TableView model setData() crashes application

I am learning Qt and I am developing Minesweeper alike game now.

For displaying game board I am using QTableView with my custom model that extends QAbstractTableModel.

Displaying data from model works well. I have overloaded QVariant data(const QModelIndex &index, int role) and all cells are displaying their "content" properly.

Now I would like to handle game board clicks and pass any data to the model.

I have overloaded setData() function:

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

and handled TableView clicks:

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
    });
}

but tableView->model()->setData() causes application to crash:

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)

Am I doing something wrong? Is this a good way to achieve changes in model on mouse click events?

Upvotes: 0

Views: 995

Answers (1)

Evgeny
Evgeny

Reputation: 4010

The problem with your closure [&]. Replace this with [tableView].

Upvotes: 1

Related Questions