一个简单的模型 视图 代理的应用

先上代码啊。

祭源码

class MyListView : public QWidget
{
    Q_OBJECT
public:
    MyListView()
    {
        data << " 111" << " 222" <<" 333";
        model = new QStringListModel(this);
        model->setStringList(data);

        listView = new QListView(this);
        listView->setModel(model);
        listView->setItemDelegate(new SpinBoxDelegate(listView));

//        QObject::connect(listView, QListView::clicked, this, MyListView::removeData);

        QVBoxLayout * mainLayout = new QVBoxLayout(this);
        mainLayout->addWidget(listView);
        setLayout(mainLayout);
    }
public slots:
    void removeData(const QModelIndex &index)//用于在数据模型中定位数据。  QAbstractItemModel 是  QModelIndex的友元类有关。
    {
        model->removeRow(index.row());
    }

private:
    QStringListModel * model;
    QListView * listView;
    QStringList data;
};

起手式

上面写一个简单的模型, 视图的应用。
我们创建了一个 QStringList对象,向其中插入了几个数据;
然后将其作为 QStringListModel的底层数据。
然后再创建QListView,使用创建好的model作为数据支撑。
最后加入 mainLayout中显示,一个Widget 就创建好。只需要show 一下就行。

扩展式

后来,我们遇到一个问题。我想接受用户的输入,而且只能输入0~100的整数,怎么办?上代理。

class SpinBoxDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public :
    SpinBoxDelegate(QObject * parent = 0) : QStyledItemDelegate(parent) {}
    //返回一个组件。该组件会被作为用户编辑数据时所使用的编辑器
    QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const
    {
        QSpinBox * editor = new QSpinBox(parent);
        editor->setMinimum(0);
        editor->setMaximum(100);
        return editor;
    }

    //从模型中获取数值,提供上述组件在显示时所需要的默认值
    void setEditorData(QWidget * editor, const QModelIndex & index) const
    {
        int value = index.model()->data(index, Qt::EditRole).toInt();
        QSpinBox * spinBox = static_cast<QSpinBox*>(editor);
        spinBox->setValue(value);
    }

    //返回给模型用户修改后的数据
    void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index)const
    {
        QSpinBox * spinBox = static_cast<QSpinBox*>(editor);
        spinBox->interpretText();//
        int value = spinBox->value();
        model->setData(index, value, Qt::EditRole);
    }

    //确保上述组件在作为编辑器时能够完整的显示出来
    void updateEditorGeometry(QWidget * edit,
                              const QStyleOptionViewItem & option,
                              const QModelIndex & ) const
    {
        edit->setGeometry(option.rect);
    }

};

点击 view 首先会进入 createEditor 函数【创建一个用户编辑时所使用的编辑器】,
然后进入 updateEditorGeometry 函数【确保组件作为编辑器时能完整显示出来】,
然后在进入setEditorData 函数【从模型中获取数值,并将数值填充到spinBox中】,
编辑完成后,会进入 setModelData 函数【将编辑器spinBox中的数值写入model中】

在这里插入图片描述

如果你调试一下,更能看出函数的调用流程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值