【问题标题】:Adding a 'None' option to a QComboBox linked to a model向链接到模型的 QComboBox 添加“无”选项
【发布时间】:2012-04-04 03:54:10
【问题描述】:

我有一个 QComboBox,因此用户可以从模型列中获取网络名称。我正在使用这样的代码:

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

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

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

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

【问题讨论】:

    标签: qt qt4 pyqt pyside


    【解决方案1】:

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

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

    【讨论】:

    • 实际上我创建了一个新的 QAbstractListModel 子类,而不是对我的主模型进行子类化。然后我将我的主模型传递给构造函数,以便新模型可以访问现有模型的数据。尽管如此,这个答案让我走上了正确的道路,在其他情况下,将原始模型类子类化可能会更好。接受。
    • 很高兴这个答案对你有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2021-04-12
    • 2013-08-09
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多