如何访问Qt::D isplayRole并在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并在 QMLTableViewColumn中指定我想要的列。

我想在

TableView {
model: fileSystemModel
TableViewColumn {
role: //what comes here?
}
}

如果要在委托中进行访问,则必须使用返回QModelIndexstyleData.index并向其传递角色的值,在这种情况下,Qt::DisplayRole根据文档0

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(( 的方法,它返回一个 QHash 和默认角色的名称(例如 DysplayRole、DecorationRole、EditRole 等(。 参见:https://doc.qt.io/qt-5/qabstractitemmodel.html#roleNames.准确地说,QFileSystemModel在QAbstracItemModel之上定义了自己的角色。参见: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;
}

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

相关内容

最新更新