学习Qt5(8)

1.模型视图框架

    1)MVC设计模式是起源于Smalltalk的一种和用户界面有关的设计模式;

    2)优点:可以有效的分离数据和用户界面;

    3)三要素:模型、视图和用户界面上的操作控制;

    4)Qt优化了MVC,采用视图和控制相结合的方式进行处理;

    5)基础模型类:QProxyModel、QAbstractListModel、QAbstractTableModel、QAbstractProxyModel、QDirModel等;

    6)基础视图类:QColumnView、QHeaderView、QListView、QTableView、QTreeView,其中QListWidget、QTableWidget、QTreeWidget是模型和视图集成在一起的类;

    7)基础代理类:QItemDelegate、QStyledItemDelegate。

 

2.代码示例:

    QDirModel model;
    QTreeView tree;
    QListView list;
    QTableView table;
 
    tree.setModel(&model);
    list.setModel(&model);
    table.setModel(&model);
    tree.setSelectionMode(QAbstractItemView::MultiSelection);
    list.setSelectionModel(tree.selectionModel());
    table.setSelectionModel(tree.selectionModel());
    QObject::connect(&tree, SIGNAL(doubleClicked(QModelIndex)), &list, SLOT(setRootIndex(QModelIndex)));
    QObject::connect(&tree, SIGNAL(doubleClicked(QModelIndex)), &table, SLOT(setRootIndex(QModelIndex)));
 
    QSplitter *splitter = new QSplitter;
    splitter->addWidget(&tree);
    splitter->addWidget(&list);
    splitter->addWidget(&table);
    splitter->setWindowTitle(QObject::tr("模型视图"));
 

3.代理代码示例

QWidget *DateDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QDateTimeEdit *editor = new QDateTimeEdit(parent);
    editor->setDisplayFormat("yyyy-MM-dd");
    editor->setCalendarPopup(true);
    editor->installEventFilter(const_cast<DateDelegate*>(this));
    return editor;
}
 
void DateDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString dateStr= index.model()->data(index).toString();
    QDate date = QDate::fromString(dateStr, Qt::ISODate);
 
    QDateTimeEdit *edit=static_cast<QDateTimeEdit*>(editor);
    edit->setDate(date);
}
 
void DateDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QDateTimeEdit *edit = static_cast<QDateTimeEdit*>(editor);
    QDate date = edit->date();
    model->setData(index,QVariant(date.toString(Qt::ISODate)));
}
 
void DateDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值