我使用QSqlTableModel在視圖中顯示SQL表。使用代理將虛擬列添加到Qt SQL模型
我想顯示基於該行數據的附加狀態列中,我使用自定義QIdentityProxyModel,我增加信息columnCount並返回數據對於不中存在新的虛擬列QSqlTableModel。
int MyProxyModel::columnCount(const QModelIndex& parent) const
{
return sourceModel() ? (sourceModel()->columnCount() + 1) : 0;
}
QVariant MyProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section == columnCount()-1 &&
orientation == Qt::Horizontal &&
role == Qt::DisplayRole)
{
return tr("MyHeader");
}
return QIdentityProxyModel::headerData(section, orientation, role);
}
QVariant MyProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
qDebug() << "data " << proxyIndex.row() << proxyIndex.column();
// ...never called for my extra column (== columnCount()-1)
if (proxyIndex.column() == columnCount()-1 && role == Qt::DisplayRole)
return QString("I am virtual");
return QIdentityProxyModel::data(proxyIndex, role);
}
編輯:我改變了代碼的東西更簡單的關於向意見。我仍然有同樣的問題。
我的問題是,鑑於從不要求數據爲我虛擬列,它調用數據()爲實際的SQL表的所有其他列,但不是最後一個虛擬的,你有什麼我錯過了什麼? 此外,標題數據對於我的額外列運行良好,問題僅在於數據。該視圖繪製額外的列,但內容是空的(即使交替行背景未被繪製)。 Thx!
'm_mySqlTableColumnCount'的值是什麼? – Mike
嘗試實現'columnCount'到'返回QIdentityProxyModel :: columnCount()+ 1;',這樣你就可以避免錯誤的值分配給你的'm_mySqlTableColumnCount'。 – Mike
@Mike這就是我最初做的,但有一些原因,我的應用程序崩潰了無數次調用'columnCount'的堆棧。我使用'sourceModelChanged'信號確保我的值是正確的,我檢查了這個值並且它很好,我的列計數返回了良好的值。 – ymoreau