wazza wazza - 1 year ago 97
C++ Question

Unable to obtain sender object in slot of dataChanged signal of QAbstractItemModel

I have subclassed QAbstractItemModel and trying to retrieve a widget in slot of dataChanged signal.

connect(model, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(slotDataChanged(const QModelIndex&, const QModelIndex&)));

void MyEditor::slotDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
QComboBox* widget = dynamic_cast<QComboBox*>(sender());
if (widget)
// do something

Here I am getting a null widget everytime, same result with qobject_cast.

I am setting combobox widget in my tableview a delegate class which derives QStyledItemDelegate.

MyDelegate* myDelegate;
myDelegate = new MyDelegate();

QWidget* MyDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
QComboBox* cb = new QComboBox(parent);
return cb;

How can i sender object in this case? Thanks.

Answer Source

Not sure of what are your intentions. Acquiring the editor widget when the data is already updated in the model is unnecessary in general. Seems to me that a brief introduction to Model-View-Delegate concept is needed to solve your problem.

In short, the view, which in your case is the QTableView, has no data by itself. View acquires data from the attached model by calling data method. When user tries to edit some data, delegate createEditor and setEditorData methods are called. The latter has model pointer as one of the arguments so it can access actual data which needs to be represented.

When user finishes editing setModelData is called which has the editor widget available to acquire the updated value. It also has the model available to change the proper data entry normally done via setData method. At this point the dataChanged signal is emitted which notifies the view that corresponding data was updated so it can refresh the displayed value(s).

Hence, try rethinking your design. Maybe what you want to achieve can be implemented differently or your implementation can be slightly modified to conform the described flow.

You can also check the Qt site for Star Delegate Example to see some sample implementations or Model View Tutorial for a broader description of the Model-View topic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download