[Qt] difference between QItemSelectionModel::selectedIndexes () and QItemSelectionModel::selectedRows ( int column = 0 )

本文探讨了在Qt中使用QItemSelectionModel类的selectedIndexes()与selectedRows()方法的区别。前者返回所有选定单元格的索引,可能包含重复项;后者则返回选定行的索引,适用于按行选择的情况。

 

摘自Qt 4.7 docs


QModelIndexList QItemSelectionModel::selectedIndexes () const

Returns a list of all selected model item indexes. The list contains no duplicates, and is not sorted.

QModelIndexList QItemSelectionModel::selectedRows ( int column = 0 ) const

Returns the indexes in the given column for the rows where all columns are selected.

This function was introduced in Qt 4.2.

See also selectedIndexes() and selectedColumns().

 

 


 

 

PS: 下面的是根据我自己的经验写出的, 请谨慎对待其参考性.

 

 

下面有段代码,用QItemSelectionModel::selectedIndexes ()时indexlist.size()的大小是总item的indexes个数,因为在构造函数当中把表的选择行为设置了SelectionRows (cardView->setSelectionBehavior(QAbstractItemView::SelectRows);), 而每行又有5列,所以每选择一行时indexlist : QItemIndexList总是多出4个重复的index出来, 即当选择一行时,本来indexlist.size()应该是等于1的 (因为只选了一行),但由于selectedIndexes()是针对表中的单元格, 而不是单元格上对应的行, 所以当选择一行时, 根据之前设置了的行为, indexlist.size()就等于该行所拥有的总列数. 而当把函数换成QItemSelectionModel::selectedRows()时便不会有这样的错误,因为这个函数是针对行的,选择了多少行即多少行。

 

 

 

 

 

QVariant attendanceRecordModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.column() == 7) { if (role == Qt::EditRole || role == Qt::DecorationRole || role == Qt::DisplayRole) { QByteArray imageData = QSqlTableModel::data(index, Qt::EditRole).toByteArray(); if (role == Qt::EditRole || role == Qt::DisplayRole) { return imageData; } if (!imageData.isEmpty()) { QPixmap pixmap; if (pixmap.loadFromData(imageData)) { return pixmap.scaled(130, 110, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); } } } return QVariant(); } //编辑和显示模式确保模型可以拿到数据 if (role == Qt::DisplayRole || role == Qt::EditRole) { return QSqlTableModel::data(index, role); } return QVariant(); } QVariant attendanceRecordModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::CheckStateRole && orientation == Qt::Horizontal && section == 8) { if (selectedIds.size() == rowCount()) return Qt::Checked; else if (selectedIds.isEmpty()) return Qt::Unchecked; else return Qt::PartiallyChecked; } if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return "序号"; case 1: return "工号"; case 2: return "姓名"; case 3: return "设备编号"; case 4: return "部门"; case 5: return "考勤状态"; case 6: return "打卡时间"; case 7: return "照片"; default: return QVariant(); } } return QVariant(); }在这个代码的基础上修改,让第九列显示复选框,同时表头也要有复选框,显示全选+复选框
07-16
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值