读Qt示例之addressbook(一)

来源:互联网 发布:如何看端口通不通 编辑:程序博客网 时间:2024/06/07 20:41

读Qt示例之addressbook(一)

这里写图片描述
这里看的示例是QT5.6.2的
addressbook 是将联系人按英文字母顺序,3个字母一组显示联系人及其地址的一个示例。
address book 包含5个类: MainWindow, AddressWidget, TableModel, NewAddressTab and AddDialog. MainWindow class u使用 AddressWidget 作为它的中心部件并且提供文件和工具菜单

这一篇主要讲讲代理模型QSortFilterProxyModel,
QSortFilterProxyModel就是插入在model与view之间,起到对模型中的数据进行排序或者过滤,然后提供给视图进行显示的作用。
AddressWidget中有这样个函数

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);//这里是匹配以str中存储的三个字母中任意一个开头的字符串,如果没有这个规则,则ABC里也会显示以X开头的        proxyModel = new QSortFilterProxyModel(this);        proxyModel->setSourceModel(table);//插入        proxyModel->setFilterRegExp(QRegExp(regExp, Qt::CaseInsensitive));//设置过滤规则并大小写敏感        proxyModel->setFilterKeyColumn(0);//以第0列过滤        QTableView *tableView = new QTableView;        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);    }}