I have the same issue. First, I confirmed that QSqlRelationalTableModel::data() returns the related string and not the key, irrespective whether role = Qt::DisplayRole or Qt::EditRole .
tableModel->select();
qDebug() << "*** Qt::DisplayRole ***";
for (int c
(0); c < tableModel
->columnCount
(QModelIndex());
++c
) qDebug
() << tableModel
->data
(tableModel
->index
(0, c,
QModelIndex()), Qt
::DisplayRole);
qDebug() << "*** Qt::EditRole ***";
for (int c
(0); c < tableModel
->columnCount
(QModelIndex());
++c
) qDebug
() << tableModel
->data
(tableModel
->index
(0, c,
QModelIndex()), Qt
::EditRole);
qDebug() << "*** record ***";
qDebug() << tableModel->record(0);
tableModel->select();
qDebug() << "*** Qt::DisplayRole ***";
for (int c(0); c < tableModel->columnCount(QModelIndex()); ++c) qDebug() << tableModel->data(tableModel->index(0, c, QModelIndex()), Qt::DisplayRole);
qDebug() << "*** Qt::EditRole ***";
for (int c(0); c < tableModel->columnCount(QModelIndex()); ++c) qDebug() << tableModel->data(tableModel->index(0, c, QModelIndex()), Qt::EditRole);
qDebug() << "*** record ***";
qDebug() << tableModel->record(0);
To copy to clipboard, switch view to plain text mode
I currently consider the following workaround:- retrieve the related table
- find the index in the related table that matches the string returned by the main table
- retrieve the key from the same row of the related table.
The following code demonstrates my approach (in my case, tableModel has a foreign key in first column = column 0; the related table has its primary key in column 0 and the string in second column = column 1)
QModelIndex idx
= relatedTable
->match
(relatedTable
->index
(0,
1),Qt
::DisplayRole, tableModel
->data
(tableModel
->index
(0,
0,
QModelIndex()), Qt
::DisplayRole)).
at(0);
qDebug
() << relatedTable
->data
(relatedTable
->index
(idx.
row(),
0,
QModelIndex()), Qt
::DisplayRole);
QSqlTableModel* relatedTable = tableModel->relationModel(0);
QModelIndex idx = relatedTable->match(relatedTable->index(0, 1),Qt::DisplayRole, tableModel->data(tableModel->index(0, 0, QModelIndex()), Qt::DisplayRole)).at(0);
qDebug() << relatedTable->data(relatedTable->index(idx.row(), 0, QModelIndex()), Qt::DisplayRole);
To copy to clipboard, switch view to plain text mode
It is not elegant. And it works only if one knows which columns have relations (i.e., qobject_casts are needed in a library where the function gets a QAbstractItemModel* that may or may not be a QSqlRelationalTableModel)
I appreciate if anybody has a cleaner solution. A role flag such as Qt::DisplayRoleRaw would be nice.
Al_
Bookmarks