Qt模型视图结构4_代理

代理说明

代理使用的类为QStyledItemDelegate.自定义代理需要实现以下4个函数:

图片名称

自定义代理四个函数的说明

四个函数的原型:

virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const
virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
  1. createEditor函数返回的是QWidget,因此可创建的代理可以是多个控件的组合。
  2. 数据保存到模型
    setModeldata函数在当前item失去焦点后被调用,而不是从下拉框中选中某项即可选中。另外,在关闭窗口后也会调用此函数,将最后的设置保存到模型中。
    QStandardItemModel中有itemChanged信号,当当前item被修改后发射信号,信号的发送在setModeldata函数调用之前,因此也则可以在此保存模型中修改的参数。

自定义代理的关键代码

QWidget *QWComboBoxDelegate::createEditor(QWidget *parent,
       const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QComboBox *editor = new QComboBox(parent);
    editor->addItem("优");
    editor->addItem("良");
    editor->addItem("一般");
    editor->addItem("不合格");
    return editor;
}

//将模型的数据设置到代理控件中
void QWComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString str = index.model()->data(index, Qt::EditRole).toString();
    QComboBox *comboBox = static_cast<QComboBox*>(editor);
    comboBox->setCurrentText(str);
}

//将代理控件的选择数据设置到模型中
void QWComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *comboBox = static_cast<QComboBox*>(editor);
    QString str = comboBox->currentText();
    model->setData(index, str, Qt::EditRole);
}

void QWComboBoxDelegate::updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

设置代理的关键代码

ui->tableView->setItemDelegate(QAbstractItemDelegate *delegate)//设置所有的单元格
ui->tableView->setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate);//设置固定的列的代理
ui->tableView->setItemDelegateForRow(int row, QAbstractItemDelegate *delegate)//设置固定行的代理

原文链接: https://www.cnblogs.com/wsw2022/p/17084405.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Qt模型视图结构4_代理

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/315277

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午1:40
下一篇 2023年2月16日 下午1:42

相关推荐