如何访问 Qt::DisplayRole 并在 TableView 中指定列

How to access Qt::DisplayRole and specify columns in 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?
 }
}

如果你想在委托中访问你必须使用 styleData.index 那 returns QModelIndex 并传递给它角色的值,在这种情况下 Qt::DisplayRole 根据 docs0:

view.model.data(styleData.index, 0)

如果你知道父级的行、列和QModelIndex:

view.model.data(view.model.index(row, colum, ix_parent), 0)

如果您打算多次重用模型,可以考虑子类化 QFileSystemModel 并添加自定义角色:

class FileSystemModel : public QFileSystemModel
{
public:

    explicit FileSystemModel(QObject *parent = nullptr) : QFileSystemModel(parent) {}

    enum Roles {
        FileSizeRole = Qt::UserRole + 1
    };

    QVariant data(const QModelIndex &index, int role) const
    {
        switch (role) {
        case FileSizeRole:
            return QFileSystemModel::data(this->index(index.row(), 1, index.parent()),
                                          Qt::DisplayRole);
        default:
            return QFileSystemModel::data(index, role);
        }
    }

    QHash<int, QByteArray> roleNames() const
    {
        auto result = QFileSystemModel::roleNames();
        result.insert(FileSizeRole, "fileSize");
        return result;
    }
};

这样,您可以简单地通过名称来引用角色:

TreeView {
    model: fsModel
    anchors.fill: parent

    TableViewColumn {
        role: "display"
    }
    TableViewColumn {
        role: "fileSize"
    }
}

QFileSystemModel 继承自 QAbstractItemModel,它有一个名为 roleNames() 的方法,returns 一个带有默认角色名称的 QHash(例如 DysplayRole、DecorationRole、EditRole 等)参见:https://doc.qt.io/qt-5/qabstractitemmodel.html#roleNames. To be accurate, QFileSystemModel defines its own roles on top of the QAbstracItemModel ones. see: https://doc.qt.io/qt-5/qfilesystemmodel.html#Roles-enum

因此,如果您没有定义任何自定义角色,那么您可以在 QML 文件中使用默认名称 (display) 简单地引用显示角色。像这样:

TableView {
  model: fileSystemModel
 TableViewColumn {
   role: "display"
 }
}

就是说,如果您定义自定义角色,则必须重写 roleNames() 方法,以便为您定义的新角色命名。在那种情况下,为了与父 class 保持一致,您应该首先调用 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;
}

您也可以简单地使用 model.displaydisplay 从任何模型中获取 DisplayRole。