QTableView::selectionChanged connect with C++11 lambdas
-
In order to catch the QTableView:::selectionChnaged signal I would like to use connect with C++11 lambdas. I tried the following:
connect(ui->tableView, QOverload<QItemSelection &, QItemSelection &>::of(ui->tableView->selectionChanged()), [=](QItemSelection &selected, QItemSelection &deselected) { on_selectionChanged(selected, deselected); });
but I get the following error from the compiler:
.../widgetaddress.cpp:32: Fehler: invalid use of non-static member function ‘virtual void QTableView::selectionChanged(const QItemSelection&, const QItemSelection&)’
32 | connect(ui->tableView, QOverload<QItemSelection &, QItemSelection &>::of(ui->tableView->selectionChanged),If I use the old connect style like this:
connect( ui->tableView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(on_selectionChanged(const QItemSelection &, const QItemSelection &)) );
it is working.
What am I doing wrong here?
-
You're trying to connect to the view, while the signal is emitted by the selection model (as in your macro version). You're also missing consts and the
QOverload
is not needed:connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, [=](const QItemSelection &selected, const QItemSelection &deselected) { on_selectionChanged(selected, deselected); });
Btw. I would strongly advise to add a third parameter to the connect to scope the life of the connection. Also this lambda seems unnecessary, as you can do just
connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &YourClassName::on_selectionChanged);
-
No need to use QOverload at all here since there is no other selectionChanged() function except selectionChanged(const QItemSelection &selected, const QItemSelection &deselected). But you're trying to use selectionChanged(QItemSelection &selected, QItemSelection &deselected) which does not exist.
-
Thanks.
What is the cleanest way to get the value of the selected item? I did it like this:
int selectedRow = ui->tableView->selectionModel()->currentIndex().row(); qDebug() << "Selected Row:" << selectedRow; QModelIndex addressIdIndex = m_addressModel->index(selectedRow, 0, QModelIndex()); QVariant addressId = m_addressModel->data(addressIdIndex, Qt::DisplayRole); qDebug() << "addressId:" << addressId.toString();
Is there a cleaner way to get the addressId?
-
Current item and selected item are not the same, so don't use current item for selection.
In a single selection model you can get selected value like this:if (ui->tableView->selectionModel()->hasSelection()) { QVariant addressId = ui->tableView->selectionModel()->selectedRows().first().data(); }
-
@infinity said in QTableView::selectionChanged connect with C++11 lambdas:
How can I set the model to single selection?
By taking a look into the documentation: https://doc.qt.io/qt-5/qabstractitemview.html#selectionBehavior-prop