将'None'选项添加到链接到模型的 QComboBox



我有一个QComboBox,这样用户就可以从模型列中获得网络名称。我使用的代码是这样的:

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

我正在使用PySide,但这确实是一个Qt问题。使用C++的答案很好。

我需要给用户不选择任何网络的选项。我想做的是在组合框中添加一个名为"无"的额外项目。但是,这只会被模型内容覆盖。

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

一个可能的解决方案是对您正在使用的模型进行子类化,以便在其中添加额外的项。实施是直接的。如果您将模型称为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
} 

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

最新更新