c++ - 如何访问 Qt::DisplayRole 并在 TableView 中指定列
问题描述
QFileSystemModel
具有以下功能data
:
Variant QFileSystemModel::data(const QModelIndex &index, int role) const
{
Q_D(const QFileSystemModel);
if (!index.isValid() || index.model() != this)
return QVariant();
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
switch (index.column()) {
case 0: return d->displayName(index);
case 1: return d->size(index);
case 2: return d->type(index);
case 3: return d->time(index);
我想知道如何DisplayRole
在 QML 中访问并指定我想要的列TableViewColumn
。
我想用它
TableView {
model: fileSystemModel
TableViewColumn {
role: //what comes here?
}
}
解决方案
QFileSystemModel 继承自 QAbstractItemModel,它有一个名为 roleNames() 的方法,它返回一个带有默认角色名称的 QHash(例如 DysplayRole、DecorationRole、EditRole 等),请参见:https ://doc.qt.io/qt- 5/qabstractitemmodel.html#roleNames。准确地说,QFileSystemModel 在 QAbsracItemModel 之上定义了自己的角色。见:https ://doc.qt.io/qt-5/qfilesystemmodel.html#Roles-enum
因此,如果您没有定义任何自定义角色,那么您可以简单地在 QML 文件中使用其默认名称(显示)来引用显示角色。像这样:
TableView {
model: fileSystemModel
TableViewColumn {
role: "display"
}
}
也就是说,如果您定义自定义角色,则必须覆盖该 roleNames() 方法,以便为您定义的新角色命名。在这种情况下,为了保持与父类的一致性,您应该首先调用 QAbstractItemModel::roleNames() 方法(在您的情况下为 QFileSystemModel::roleNames()),然后在返回的 QHash 中设置新的角色名。这是我定义主机、用户名和密码角色的登录项的示例:
QHash<int, QByteArray> LoginModel::roleNames() const
{
QHash<int,QByteArray> names = QAbstractItemModel::roleNames();
names[HostRole] = "host";
names[UsernameRole] = "username";
names[PasswordRole] = "password";
return names;
}
推荐阅读
- algorithm - 协助计算调用其他函数的函数的时间复杂度
- visual-studio - “未配置 NDK。” 在 Visual Studio 代码中
- c# - 我可以在哪里存储用户在 c# 中提供的连接字符串?
- regex - 在postgres中的正则表达式匹配后从列中提取信息
- firebase - Firestore 快照侦听器 - fromCache 值不一致
- python - 从具有 2 个公共键的字典列表中构建新字典的最有效方法?
- asp.net-core - Web Api 中是否可以使用 DuplicatePropertyNameHandling?
- r - 一次合并两个以上的数据帧
- linux - 如何使用 awk 打印除特定字段之外的所有字段?
- php - 在php中确定类子类型