PDA

View Full Version : QModelIndex Mapping in Template QWidget Class



stefanadelbert
1st March 2010, 08:02
I have created a template class that inherits from QWidget and aggregates a sortable QTableView and a QSortFilterProxyModel. I want to be able to react to a double click in the QTableView and pass the QModelIndex to my custom model, which has the slot void DoubleClicked(const QModelIndex&) defined on it.

This is a slimmed down version of the template class:



template<typename MODEL>
class TTableViewWidget : public QWidget
{
public:
TTableViewWidget(MODEL& m, QWidget* parent = 0) :
QWidget(parent),
model(m)
{
sortProxy.reset(new QSortFilterProxyModel(this));
sortProxy->setSourceModel(&model);

SetupUI();

connect(tableView.get(), SIGNAL(doubleClicked(const QModelIndex&)),
&model, SLOT(DoubleClicked(const QModelIndex&)));
}
~TTableViewWidget() {}

private:
void SetupUI() {
tableView.reset(new QTableView(this));
tableView->setSortingEnabled(true);
tableView->setModel(sortProxy.get());

verticalLayout.reset(new QVBoxLayout(this));
verticalLayout->addWidget(tableView.get());
}

private:
std::auto_ptr<QVBoxLayout> verticalLayout;
std::auto_ptr<QTableView> tableView;
std::auto_ptr<QSortFilterProxyModel> sortProxy;

private:
MODEL& model;

};

The problem is that a QTableView::doubleClicked signal returns a QModelIndex that needs to be mapped using the QSortFilterProxyModel. Q_OBJECT does not handle template classes, so I'm not able to define signals or slots in my template class, otherwise I could simply do the mapping in a slot on the template class.

One idea I had was the subclass a QSortFilterProxyModel and provide a DoubleClicked slot that would map and call into its source model. Does anyone else have any clever ideas?

stefanadelbert
1st March 2010, 08:19
It seems there are answers out there. For example, http://doc.trolltech.com/qq/qq15-academic.html#connectingtotemplates,


If the signals and slots don't require the template parameter to be part of the prototype, the workaround is to make a template class inherit a QObject subclass that provides the required signals and slots: