我想向 QFileSystemModel 添加自定义角色(可能是派生模型)。我想使用此角色来保存复选框的选中状态,该状态显示在自定义委托(delegate)中的文件名旁边。如何做到这一点?
最佳答案
我已经使用了示例 Qt Quick Controls - File System Browser Example删除部分选择。
步骤如下:
在
roleNames
中添加新角色:QHash<int,QByteArray> roleNames() const Q_DECL_OVERRIDE { QHash<int, QByteArray> result = QFileSystemModel::roleNames(); result.insert(SizeRole, QByteArrayLiteral("size")); result.insert(DisplayableFilePermissionsRole, QByteArrayLiteral("displayableFilePermissions")); result.insert(LastModifiedRole, QByteArrayLiteral("lastModified")); result.insert(Qt::CheckStateRole, QByteArrayLiteral("checkRole")); return result; }
创建一个存储选择信息的容器,在本例中我将使用
QMap
:QMap<QPersistentModelIndex, Qt::CheckState> m_checks;
如果存储在容器中则覆盖返回状态的
data()
方法,如果不返回Qt::UnChecked
为默认值:QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE { if (index.isValid() && role >= SizeRole) { ... } else if (role == Qt::CheckStateRole) { QPersistentModelIndex pix(index); if(m_checks.contains(pix)){ return m_checks[pix]; } return Qt::Unchecked; } return QFileSystemModel::data(index, role); }
覆盖
setData()
方法,如有必要,您必须修改该方法并创建数据。bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole){ if(role == Qt::CheckStateRole && index.isValid()){ Qt::CheckState current = value.value<Qt::CheckState>(); if(m_checks.contains(index)){ Qt::CheckState last = m_checks[index]; if(last == current) return false; m_checks[index] = current; } else{ m_checks.insert(index, current); } emit dataChanged(index, index, {role}); return true; } return QFileSystemModel::setData(index, value, role); }
我添加了一个新列,在其中建立了对
CheckBox
的委托(delegate),并使用onCheckedChanged
插槽通过设置值setData()
方法,传递QModelIndex
、数据和角色,在本例中传递 10,因为它是Qt::CheckStateRole
的值编号>.TreeView { id: view model: fileSystemModel ... TableViewColumn { role: "checkRole" delegate: Component { CheckBox { id: mycbx checked: styleData.value onCheckedChanged: view.model.setData(styleData.index, checked, 10) } } } ...
完整的示例可以在下面的link中找到。 .
关于c++ - 如何向 QFileSystemModel 添加自定义角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50178597/