QSqlRelationalDelegate subclass that works with QSqlRelationalTableModel
When you are using a QSqlRelationalTableModel in combination with QSortFilterProxyModel, you loose the automatic combobox that is displayed in a QTableView.
This is a subclass of QSqlRelationalDelegate, that works:
COMMENT: To use it with another proxy model (my own QXTreeProxyModel that converts a table to a tree that can be displayed by QTreeView), I replaced QSortFilterProxyModel by QAbstractProxyModel throughout the code in mysqlrelationaldelegate.cpp; no other changes were necessary. BTW, QXTreeProxyModel is available on https://github.com/Al-/QXTreeProxyModel
Header:
- #ifndef MYSQLRELATIONALDELEGATE_H
- #define MYSQLRELATIONALDELEGATE_H
- #include <QSqlRelationalDelegate>
- {
- Q_OBJECT
- public:
- QWidget *createEditor(QWidget *aParent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
- signals:
- public slots:
- };
- #endif // MYSQLRELATIONALDELEGATE_H
Source:
- #include "mysqlrelationaldelegate.h"
- #include <QSqlRelationalTableModel>
- #include <QSortFilterProxyModel>
- #include <QDebug>
- #include <QSqlRecord>
- {
- }
- QWidget *mySqlRelationalDelegate::createEditor(QWidget *aParent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
- const QSqlRelationalTableModel *sqlModel = qobject_cast<const QSqlRelationalTableModel *>(index.model());
- if (!childModel )
- {
- const QSortFilterProxyModel* proxyModel = qobject_cast<const QSortFilterProxyModel *>(index.model());
- if (proxyModel)
- {
- childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
- }
- }
- if (!childModel)
- {
- }
- combo->setModel(childModel);
- combo->setModelColumn(childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()));
- combo->installEventFilter(const_cast<mySqlRelationalDelegate *>(this));
- return combo;
- }
- {
- const QSqlRelationalTableModel *sqlModel = qobject_cast<const QSqlRelationalTableModel *>(index.model());
- if (!sqlModel )
- {
- const QSortFilterProxyModel* proxyModel = qobject_cast<const QSortFilterProxyModel *>(index.model());
- if (proxyModel) {
- strVal = proxyModel->data(index).toString();
- }
- } else {
- strVal = sqlModel->data(index).toString();
- }
- if (strVal.isEmpty() || !combo) {
- return;
- }
- combo->setCurrentIndex(combo->findText(strVal));
- }
- void mySqlRelationalDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
- {
- if (!index.isValid())
- return;
- if (!sqlModel )
- {
- if (proxyModel)
- }
- if (!sqlModel || !childModel || !combo) {
- return;
- }
- int currentItem = combo->currentIndex();
- int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn());
- int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn());
- if (proxyModel) {
- } else {
- }
- }

