我想向 QFileSystemModel 添加自定义角色(可能是派生模型)。我想使用此角色来保存复选框的选中状态,该状态显示在自定义委托中的文件名旁边。如何才能做到这一点?
我已经使用过使用示例Qt Quick Controls - 文件系统浏览器示例 https://doc.qt.io/qt-5.10/qtquickcontrols-filesystembrowser-example.html删除选择的部分。
步骤如下:
-
添加新角色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
我用了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 https://github.com/eyllanesc/stackoverflow/tree/master/50178597-filesystembrowser.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)