Qt 添加一个';无';链接到模型的QComboBox的选项

Qt 添加一个';无';链接到模型的QComboBox的选项,qt,qt4,pyqt,pyside,Qt,Qt4,Pyqt,Pyside,我有一个QComboBox,用户可以从模型列中输入网络名称。我使用的代码如下: self.networkSelectionCombo = QtGui.QComboBox() self.networkSelectionCombo.setModel(self.model.worldLinks) self.networkSelectionCombo.setModelColumn(WLM.NET_NAME) 我正在使用PySide,但这确实是一个Qt问题。使用C++的答案很好。 我需要给用户不选择任何

我有一个QComboBox,用户可以从模型列中输入网络名称。我使用的代码如下:

self.networkSelectionCombo = QtGui.QComboBox()
self.networkSelectionCombo.setModel(self.model.worldLinks)
self.networkSelectionCombo.setModelColumn(WLM.NET_NAME)
我正在使用PySide,但这确实是一个Qt问题。使用C++的答案很好。 我需要给用户不选择任何网络的选项。我想做的是在组合框中添加一个名为“无”的额外项。但是,这将被模型内容覆盖


我能想到的唯一方法是在这个模型列上创建一个中间自定义视图,并使用它来更新组合,然后视图可以处理添加额外的“magic”项。有人知道一种更优雅的方法吗?

一种可能的解决方案是对正在使用的模型进行子类化,以便在其中添加额外的项。实施是直接的。如果调用模型
MyModel
,则子类将如下所示(使用C++):


现在可以将此模型设置为组合框

我实际上创建了一个新的QAbstractListModel子类,而不是主模型的子类。然后,我将主模型传递给构造函数,以便新模型可以访问现有模型的数据。尽管如此,这个答案让我走上了正确的道路,在其他情况下,子类化或原始模型类可能会更好。接受。我很高兴答案对你有帮助。
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
}