专业的编程技术博客社区

网站首页 > 博客文章 正文

Qt模型视图结构_代理(犀牛缩放视图后看不见模型了)

baijin 2024-10-24 08:50:41 博客文章 15 ℃ 0 评论

代理说明

代理使用的类为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)//设置固定行的代理

文章转自博客园(YueLiGo):https://www.cnblogs.com/wsw2022/p/17084405.html

Qt资料领取→Qt资料领取(视频教程+文档+代码+项目实战)

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表