Qt Model/View/Delegate浅谈

自作多情 提交于 2019-12-01 16:24:09

role,也就是俗称的角色.

##roleNames()函数介绍及默认值 roleNames()函数返回一个model的所有角色名称. 在Qt中默认的角色名称如下:

Qt Role QML Role Name
Qt::DisplayRole display
Qt::DecorationRole decoration
Qt::EditRole edit
Qt::ToolTipRole toolTip
Qt::StatusTipRole statusTip
Qt::WhatsThisRole whatsThis

##自定义roleNames() Qt旧版本中,可以通过setRoleNames()函数来实现自己想要的角色名,

This function is obsolete. Reimplement roleNames() instead.

但是根据Qt5.6.0新版本相关文档的介绍,该函数已经过时,需要通过重新实现roleNames()来替代setRoleNames(). 这意味着:如果我们想要自定义的角色名,则需要重新实现虚函数roleNames().

接下来,我们看看到底如何自定义roleNames():

  • 首先在头文件中添加枚举类型(注意枚举类型命名规则)
//customModel.h

#include <QAbstractItemModel>

class customModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    enum StringListRoles{
        IconRole = Qt::UserRole + 1, //都是Role结尾的
        TextRole = Qt::UserRole + 2,
        UrlRole = Qt::UserRole + 3
    }; 
    explicit customModel(QObject *parent = 0);
    ~customModel();
        
    QHash<int, QByteArray> roleNames() const; //重新实现roleNames()
}
  • 然后重新实现roleNames()
//customModel.cpp

//角色名
QHash<int, QByteArray> customModel::roleNames() const
{
    //这里插入的值需要和前面定义的枚举类型对应
    QHash<int, QByteArray> roleNames;
    roleNames.insert(customModel::IconRole, QByteArray("icon"));
    roleNames.insert(customModel::TextRole, QByteArray("text"));
    roleNames.insert(customModel::UrlRole, QByteArray("url"));
    return roleNames;
}

然后就可以自由使用自己想要的role了.

注意: QListView & QTreeView & QTableView等视图默认使用的是Qt里roleNames()返回的默认角色,所以如果想要视图识别和读取自定义的角色名,还要重新实现对应的delegate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!