2012-03-19 61 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