先来图片
这个demo主要使用了
1-QAbstractTableModel类
2-QSortFilterProxyModel类
3-QTableView类
学过java的应该知道springMVC,QT这里也使用了MVC的模式,M即Model(就是数据),V即Vision(就是界面显示),C即控制(就是代码逻辑层面)
使用QAbstractTableModel要重载至少以下3个函数,它是为视图层提供数据显示接口的
int rowCount(const QModelIndex &parent) const Q_DECL_OVERRIDE;
int columnCount(const QModelIndex &parent) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
QSortFilterProxyModel类是个过滤器,java里也有过滤器,就是过滤掉不需要的数据,只让满足要求的数据通过,我们看下代码是如何做的
void AddressWidget::setupTabs()
{
QStringList groups;
groups << "ABC" << "DEF" << "GHI" << "JKL" << "MNO" << "PQR" << "STU" << "VW" << "XYZ";
for (int i = 0; i < groups.size(); ++i) {
QString str = groups.at(i);
//过滤表达式,虽然厚些看不懂
QString regExp = QString("^[%1].*").arg(str);
proxyModel = new QSortFilterProxyModel(this);
//设置源数据
proxyModel->setSourceModel(table);
//设置过滤表达式
proxyModel->setFilterRegExp(QRegExp(regExp, Qt::CaseInsensitive));
//设置要过滤的关键列
proxyModel->setFilterKeyColumn(0);
QTableView *tableView = new QTableView;
//模型层(Model)绑定显示层(vision)
tableView->setModel(proxyModel);
//设置显示规则
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->horizontalHeader()->setStretchLastSection(true);
tableView->verticalHeader()->hide();
tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
tableView->setSelectionMode(QAbstractItemView::SingleSelection);
tableView->setSortingEnabled(true);
//和上层的交互
connect(tableView->selectionModel(),
&QItemSelectionModel::selectionChanged,
this, &AddressWidget::selectionChanged);
addTab(tableView, str);
}
}
经过过滤器的数据想要再次获取,其实也挺麻烦的,下面的代码就是想要重新编辑数据
void AddressWidget::editEntry()
{
QTableView *temp = static_cast<QTableView*>(currentWidget());
QSortFilterProxyModel *proxy = static_cast<QSortFilterProxyModel*>(temp->model());
QItemSelectionModel *selectionModel = temp->selectionModel();
QModelIndexList indexes = selectionModel->selectedRows();
QString name;
QString address;
int row = -1;
foreach (QModelIndex index, indexes) {
row = proxy->mapToSource(index).row();
QModelIndex nameIndex = table->index(row, 0, QModelIndex());
QVariant varName = table->data(nameIndex, Qt::DisplayRole);
name = varName.toString();
QModelIndex addressIndex = table->index(row, 1, QModelIndex());
QVariant varAddr = table->data(addressIndex, Qt::DisplayRole);
address = varAddr.toString();
}
//! [4a]
//! [4b]
AddDialog aDialog;
aDialog.setWindowTitle(tr("Edit a Contact"));
aDialog.nameText->setReadOnly(true);
aDialog.nameText->setText(name);
aDialog.addressText->setText(address);
if (aDialog.exec()) {
QString newAddress = aDialog.addressText->toPlainText();
if (newAddress != address) {
QModelIndex index = table->index(row, 1, QModelIndex());
table->setData(index, newAddress, Qt::EditRole);
}
}
}
//! [4b]