首页 > 解决方案 > 如何访问 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?
 }
}

标签: c++qtqmlqt5qfilesystemmodel

解决方案


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;
}

推荐阅读