Search code examples
c++qtsignals-slots

Qt: Connect casted sender to a receiver


In my program, I have a QTableView which is set to display QStandardItemModel. I want to connect Model's

itemChanged(QStandardItem*)

Signal to my SLOT. I did

connect(dynamic_cast<QStandardItemModel*>(ui->tableView->model()), SIGNAL(itemChanged(QStandardItem*)), this, SLOT(saveItem(QStandardItem*)));

But this always fails to connect (returns false). I am guessing it is because of dynamic_cast but I am not sure.

What am I doing wrong??


Solution

  • Even if QTableView::model() returns a QAbstractItemModel*, if the model is set to a QStandardItemModel* before making the connection, the actual object will still be a QStandardItemModel, so the connection should work without the need to cast the pointer to that type.

    Possible connection errors include: null pointer (by not setting the model before calling model()), bad spelling of the slot/signal name, not declaring a function as a slot/signal.

    PS: It might be better to have the QStandardItemModel as a pointer member in your class, if you haven't already one, rather than using model() to retrieve it and having to repeat the cast each time you need to access the specific functions of the QStandardItemModel class.
    And as an additional benefit, the auto-completion would work since QtCreator would also know the actual object type.