📄 qdatawidgetmapper.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the QtGui module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file. Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "qdatawidgetmapper.h"#ifndef QT_NO_DATAWIDGETMAPPER#include "qabstractitemmodel.h"#include "qitemdelegate.h"#include "qmetaobject.h"#include "qwidget.h"#include "private/qobject_p.h"#include "private/qabstractitemmodel_p.h"class QDataWidgetMapperPrivate: public QObjectPrivate{public: Q_DECLARE_PUBLIC(QDataWidgetMapper) QDataWidgetMapperPrivate() : model(QAbstractItemModelPrivate::staticEmptyModel()), delegate(0), orientation(Qt::Horizontal), submitPolicy(QDataWidgetMapper::AutoSubmit) { } QAbstractItemModel *model; QAbstractItemDelegate *delegate; Qt::Orientation orientation; QDataWidgetMapper::SubmitPolicy submitPolicy; QPersistentModelIndex rootIndex; QPersistentModelIndex currentTopLeft; inline int itemCount() { return orientation == Qt::Horizontal ? model->rowCount(rootIndex) : model->columnCount(rootIndex); } inline int currentIdx() const { return orientation == Qt::Horizontal ? currentTopLeft.row() : currentTopLeft.column(); } inline QModelIndex indexAt(int itemPos) { return orientation == Qt::Horizontal ? model->index(currentIdx(), itemPos, rootIndex) : model->index(itemPos, currentIdx(), rootIndex); } inline void flipEventFilters(QAbstractItemDelegate *oldDelegate, QAbstractItemDelegate *newDelegate) { for (int i = 0; i < widgetMap.count(); ++i) { QWidget *w = widgetMap.at(i).widget; if (!w) continue; w->removeEventFilter(oldDelegate); w->installEventFilter(newDelegate); } } void populate(); // private slots void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); void _q_commitData(QWidget *); void _q_closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint); void _q_modelDestroyed(); struct WidgetMapper { inline WidgetMapper(QWidget *w = 0, int c = 0) : widget(w), section(c) {} inline WidgetMapper(QWidget *w, int c, const QByteArray &p) : widget(w), section(c), property(p) {} QPointer<QWidget> widget; int section; QPersistentModelIndex currentIndex; QByteArray property; }; void populate(WidgetMapper &m); int findWidget(QWidget *w) const; bool commit(const WidgetMapper &m); QList<WidgetMapper> widgetMap;};int QDataWidgetMapperPrivate::findWidget(QWidget *w) const{ for (int i = 0; i < widgetMap.count(); ++i) { if (widgetMap.at(i).widget == w) return i; } return -1;}bool QDataWidgetMapperPrivate::commit(const WidgetMapper &m){ if (m.widget.isNull()) return true; // just ignore if (!m.currentIndex.isValid()) return false; if (m.property.isEmpty()) delegate->setModelData(m.widget, model, m.currentIndex); else { // Create copy to avoid passing the widget mappers data QModelIndex idx = m.currentIndex; model->setData(idx, m.widget->property(m.property), Qt::EditRole); } return true;}void QDataWidgetMapperPrivate::populate(WidgetMapper &m){ if (m.widget.isNull()) return; m.currentIndex = indexAt(m.section); if (m.property.isEmpty()) delegate->setEditorData(m.widget, m.currentIndex); else m.widget->setProperty(m.property, m.currentIndex.data(Qt::EditRole));}void QDataWidgetMapperPrivate::populate(){ for (int i = 0; i < widgetMap.count(); ++i) populate(widgetMap[i]);}static bool qContainsIndex(const QModelIndex &idx, const QModelIndex &topLeft, const QModelIndex &bottomRight){ return idx.row() >= topLeft.row() && idx.row() <= bottomRight.row() && idx.column() >= topLeft.column() && idx.column() <= bottomRight.column();}void QDataWidgetMapperPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight){ if (topLeft.parent() != rootIndex) return; // not in our hierarchy for (int i = 0; i < widgetMap.count(); ++i) { WidgetMapper &m = widgetMap[i]; if (qContainsIndex(m.currentIndex, topLeft, bottomRight)) populate(m); }}void QDataWidgetMapperPrivate::_q_commitData(QWidget *w){ if (submitPolicy == QDataWidgetMapper::ManualSubmit) return; int idx = findWidget(w); if (idx == -1) return; // not our widget commit(widgetMap.at(idx));}class QFocusHelper: public QWidget{public: bool focusNextPrevChild(bool next) { return QWidget::focusNextPrevChild(next); } static inline void focusNextPrevChild(QWidget *w, bool next) { static_cast<QFocusHelper *>(w)->focusNextPrevChild(next); }};void QDataWidgetMapperPrivate::_q_closeEditor(QWidget *w, QAbstractItemDelegate::EndEditHint hint){ int idx = findWidget(w); if (idx == -1) return; // not our widget switch (hint) { case QAbstractItemDelegate::RevertModelCache: { populate(widgetMap[idx]); break; } case QAbstractItemDelegate::EditNextItem: QFocusHelper::focusNextPrevChild(w, true); break; case QAbstractItemDelegate::EditPreviousItem: QFocusHelper::focusNextPrevChild(w, false); break; case QAbstractItemDelegate::SubmitModelCache: case QAbstractItemDelegate::NoHint: // nothing break; }}void QDataWidgetMapperPrivate::_q_modelDestroyed(){ Q_Q(QDataWidgetMapper); model = 0; q->setModel(QAbstractItemModelPrivate::staticEmptyModel());}/*! \class QDataWidgetMapper \brief The QDataWidgetMapper class provides mapping between a section of a data model to widgets. \since 4.2 \ingroup model-view QDataWidgetMapper can be used to create data-aware widgets by mapping them to sections of an item model. A section is a column of a model if the orientation is horizontal (the default), otherwise a row. Every time the current index changes, each widget is updated with data from the model via the property specified when its mapping was made. If the user edits the contents of a widget, the changes are read using the same property and written back to the model. By default, each widget's \l{Q_PROPERTY()}{user property} is used to transfer data between the model and the widget. Since Qt 4.3, an additional addMapping() function enables a named property to be used instead of the default user property. It is possible to set an item delegate to support custom widgets. By default, a QItemDelegate is used to synchronize the model with the widgets. Let us assume that we have an item model named \c{model} with the following contents: \table \row \o 1 \o Trolltech ASA \o Oslo \row \o 2 \o Trolltech Pty \o Brisbane \row \o 3 \o Trolltech Inc \o Palo Alto \row \o 4 \o Trolltech China \o Beijing \row \o 5 \o Trolltech GmbH \o Berlin \endtable The following code will map the columns of the model to widgets called \c mySpinBox, \c myLineEdit and \c{myCountryChooser}: \code QDataWidgetMapper *mapper = new QDataWidgetMapper; mapper->setModel(model); mapper->addMapping(mySpinBox, 0); mapper->addMapping(myLineEdit, 1); mapper->addMapping(myCountryChooser, 2); mapper->toFirst(); \endcode After the call to toFirst(), \c mySpinBox displays the value \c{1}, \c myLineEdit displays \c {Trolltech ASA} and \c myCountryChooser displays \c{Oslo}. The navigational functions toFirst(), toNext(), toPrevious(), toLast() and setCurrentIndex() can be used to navigate in the model and update the widgets with contents from the model. The setRootIndex() function enables a particular item in a model to be specified as the root index - children of this item will be mapped to the relevant widgets in the user interface. QDataWidgetMapper supports two submit policies, \c AutoSubmit and \c{ManualSubmit}. \c AutoSubmit will update the model as soon as the current widget loses focus, \c ManualSubmit will not update the model unless submit() is called. \c ManualSubmit is useful when displaying a dialog that lets the user cancel all modifications. Also, other views that display the model won't update until the user finishes all their modifications and submits. Note that QDataWidgetMapper keeps track of external modifications. If the contents of the model are updated in another module of the application, the widgets are updated as well. \sa QAbstractItemModel, QAbstractItemDelegate *//*! \enum QDataWidgetMapper::SubmitPolicy This enum describes the possible submit policies a QDataWidgetMapper supports. \value AutoSubmit Whenever a widget loses focus, the widget's current value is set to the item model. \value ManualSubmit The model is not updated until submit() is called. *//*! \fn void QDataWidgetMapper::currentIndexChanged(int index) This signal is emitted after the current index has changed and all widgets were populated with new data. \a index is the new current index. \sa currentIndex(), setCurrentIndex() *//*! Constructs a new QDataWidgetMapper with parent object \a parent. By default, the orientation is horizontal and the submit policy is \c{AutoSubmit}. \sa setOrientation(), setSubmitPolicy() */QDataWidgetMapper::QDataWidgetMapper(QObject *parent) : QObject(*new QDataWidgetMapperPrivate, parent){ setItemDelegate(new QItemDelegate(this));}/*! Destroys the object. */QDataWidgetMapper::~QDataWidgetMapper(){}/*! Sets the current model to \a model. If another model was set, all mappings to that old model are cleared. \sa model() */void QDataWidgetMapper::setModel(QAbstractItemModel *model){ Q_D(QDataWidgetMapper); if (d->model == model) return; if (d->model) { disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(_q_dataChanged(QModelIndex,QModelIndex))); disconnect(d->model, SIGNAL(destroyed()), this, SLOT(_q_modelDestroyed())); } clearMapping(); d->rootIndex = QModelIndex(); d->currentTopLeft = QModelIndex(); d->model = model; connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(_q_dataChanged(QModelIndex,QModelIndex))); connect(model, SIGNAL(destroyed()), SLOT(_q_modelDestroyed()));}/*! Returns the current model. \sa setModel() */QAbstractItemModel *QDataWidgetMapper::model() const{ Q_D(const QDataWidgetMapper); return d->model == QAbstractItemModelPrivate::staticEmptyModel() ? static_cast<QAbstractItemModel *>(0) : d->model;}/*! Sets the item delegate to \a delegate. The delegate will be used to write data from the model into the widget and from the widget to the model, using QAbstractItemDelegate::setEditorData() and QAbstractItemDelegate::setModelData(). The delegate also decides when to apply data and when to change the editor, using QAbstractItemDelegate::commitData() and QAbstractItemDelegate::closeEditor(). \warning You should not share the same instance of a delegate between widget mappers or views. Doing so can cause incorrect or unintuitive editing behavior since each view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()} signal, and attempt to access, modify or close an editor that has already been closed. */void QDataWidgetMapper::setItemDelegate(QAbstractItemDelegate *delegate){ Q_D(QDataWidgetMapper); QAbstractItemDelegate *oldDelegate = d->delegate; if (oldDelegate) { disconnect(oldDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(_q_commitData(QWidget*))); disconnect(oldDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), this, SLOT(_q_closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint))); } d->delegate = delegate; if (delegate) { connect(delegate, SIGNAL(commitData(QWidget*)), SLOT(_q_commitData(QWidget*))); connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), SLOT(_q_closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint))); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -