2012-03-19 38 views
4

我有一個QComboBox,因此用戶可以從模型列中獲取網絡名稱。我正在使用這樣的代碼:向鏈接到模型的QComboBox添加「無」選項

self.networkSelectionCombo = QtGui.QComboBox() 
self.networkSelectionCombo.setModel(self.model.worldLinks) 
self.networkSelectionCombo.setModelColumn(WLM.NET_NAME) 

我使用PySide,但這是一個真正的Qt問題。使用C++的答案很好。

我需要給用戶選擇不選擇任何網絡。我想要做的是在名爲'None'的組合框中添加一個額外的項目。但是這隻會被模型內容覆蓋。

我能想到的唯一方法是在這個模型列上創建一箇中間自定義視圖,並使用它來更新組合,然後視圖可以處理添加額外的'魔術'項目。有沒有人知道這樣做的更優雅的方式?

回答

3

一種可能的解決方案是對您正在使用的模型進行子類化,以便在其中添加額外的項目。實施非常簡單。如果你打電話給你的模型MyModel那麼子類看起來像這樣(用C++):

class MyModelWithNoneEntry : public MyModel 
{ 
public: 
    int rowCount() {return MyModel::rowCount()+1;} 
    int columnCount() {return MyModel::columnCOunt();} 
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const 
    { 
     if (index.row() == 0) 
     { 
      // if we are at the desired column return the None item 
      if (index.column() == NET_NAME && role == Qt::DisplayRole) 
        return QVariant("None"); 
      // otherwise a non valid QVariant 
      else 
        return QVariant(); 
     } 
     // Return the parent's data 
     else 
      return MyModel::data(createIndex(index.row()-1,index.col()), role);  
    } 

    // parent and index should be defined as well but their implementation is straight 
    // forward 
} 

現在你可以設置這個模型的組合框。

+0

整潔。我會試一試。 – 2012-03-20 15:38:53

+0

我實際上創建了一個新的QAbstractListModel子類,而不是我的主模型的子類。然後我將主模型傳遞給構造函數,以便新模型可以訪問現有模型的數據。儘管如此,這個答案讓我走上了正確的道路,在其他情況下,對原始模型類進行子類化可能會更好。公認。 – 2012-03-20 17:21:28

+0

我很高興答案幫助你。 – pnezis 2012-03-20 19:00:26