I am trying to provide a table with a specific behavior, which would be that when selecting a cell and dragging the mouse, it would only select the cells of the same column. For this, and looking at similar issues, I have tried to use a lambda function.
The thing, and here comes the question, is that if I make the connection between the selection and the function outside the constructor of the table, I don't have problems, but if I try to do it inside the constructor, I get this error:
QObject::connect: invalid null parameter
Specifically, this works for me:
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
MiTabla *tabla = new MiTabla;
tabla->setModel(new MiModelo());
tabla->setItemDelegate(new MiDelegado());
selectionModel = tabla->selectionModel();
setCentralWidget(tabla);
QObject::connect(selectionModel,&QItemSelectionModel::selectionChanged,[=]()
{
foreach (const QModelIndex& item, selectionModel->selectedIndexes())
{
if (item.column()!=tabla->indiceActual().column())
{
selectionModel->select(item,QItemSelectionModel::Deselect);
}
}
});
}
But this gives me the error mentioned above:
MiTabla::MiTabla()
{
miSelectionModel = selectionModel();
QObject::connect(this,SIGNAL(pressed(QModelIndex)),this,SLOT(CambiarIndiceACtual(QModelIndex)));
QObject::connect(miSelectionModel,&QItemSelectionModel::selectionChanged,[=]()
{
foreach (const QModelIndex& item, miSelectionModel->selectedIndexes())
{
if (item.column()!=m_indiceActual.column())
{
miSelectionModel->select(item,QItemSelectionModel::Deselect);
}
}
});
}
If we take a look at this link we see that each time a is called
setModel
a newQItemSelectionModel
. And what about the previous one? Well, since it turns out that the parent is the table itself, the object is destroyed without further ado.So if it turns out that the lambda stores a copy of a pointer to a
QItemSelectionModel
that has already been deleted the result cannot be positive at all.There is absolutely no reason to duplicate the pointer
selectionModel
. Asking it inside the lambda will save you trouble:Although the truth is that there is no need to use lambdas. A small problem with using lambdas here is that they cannot be disconnected later, which can give you problems in the future. It is more practical to create a slot in
MiTabla
: