從我所見,Qt 檔案和大多數在線示例假設我們對data(). 但是如果我的表基于自定義結構呢?例如讓我們有:
struct MyDrive
{
QString serialNo;
QString user;
QString pc;
QString ipAddress;
QString category;
};
serialNo關鍵在哪里。所以任何來自外部的操作(想象模型已經實作了一個監聽器)使用它來洗掉/修改一個專案,使其QMap成為理想的候選者。
但是如何將這個結構與QModelIndex的資料連接起來呢?QAbstractTableModel::data要求以 (column,row) 為鍵的資料,使其更適合于QVector<QVector>>或類似的東西(我讀過的地方我應該避免使用具有非恒定訪問時間的容器(如 map) in data())。
我可以想象使用具有QModelIndex作為鍵和serialNo作為值的映射,該映射將用作我的(基于serialNo 的)映射的鍵,但這看起來效率很低——QModelIndex地址具體條目(serialNo、user、pc、... ) 畢竟所以我們會一遍又一遍地復制同一個專案。我也在考慮有一張<serialNo, MyDrive*>地圖,但這只是一個丑陋的設計決定的解決方法。
我不敢相信我是第一個遇到這種情況的人,那么通常如何解決?
uj5u.com熱心網友回復:
您可以使用 QAbstractItemModel::match 通過串行qt 幫助查找專案 并將所有必要的資料輸入表中。這將允許您不使用容器,但這是一個問題的效率如何......
第二個解決方案是子類 AbstractItemModel Reference。現在您可以通過實作 data() 函式來做您想做的事情并使用任何容器。
uj5u.com熱心網友回復:
我可能誤解了您面臨的問題,但我們開始了。我假設您有很多MyDrive. 這是 QAbstractTableModel 子類的(不完整的)實作。訣竅是將正確的 MyDrive 實體傳遞給適當的 QModelIndex。當您稍后修改或訪問該索引中的資料時,您不再真正需要使用 serialNo,因為該索引的內部指標是您在創建該索引時傳遞的 MyDrive 實體:
class MyTable : public QAbstractTableModel
{
public:
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
{
auto* my_drive = static_cast<MyDrive*>(index.internalPointer());
auto drive_key = my_drive->serialNo;
// use the key if you desire for lookups etc
//...
// return your data;
}
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)
{
auto* my_drive = static_cast<MyDrive*>(index.internalPointer());
auto drive_key = my_drive->serialNo;
// use they key again if you like
}
QModelIndex index(int row, int column, const QModelIndex &parent) const
{
// insert checks here for parent and to ensure row and column are within appropriate bounds etc
// your returned index will now store your MyDrive instance which you will later access from the data and setData methods
return createIndex(row, column, m_data row);
}
private:
// array of MyDrive instances
MyDrive* m_data;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349137.html
