QAbstractListModel 在 Qt::DisplayRole 上返回意外结果

Asl*_*lam 2 c++ qt qml

我创建了一个具有两个角色的非常小的 QAbstractListModel,display并且test

InvoiceTabModel::InvoiceTabModel(QObject *parent): QAbstractListModel(parent)
{

}

QVariant InvoiceTabModel::data(const QModelIndex &index, int role) const
{
    Q_UNUSED(index)
    if(role == 123)
        return QVariant("testRole");
    return QVariant("displayRole");
}

int InvoiceTabModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 3;
}

QHash<int, QByteArray> InvoiceTabModel::roleNames() const
{
    return { {Qt::DisplayRole, "display"}, {123, "test"} };
}
Run Code Online (Sandbox Code Playgroud)

我将此模型连接到中继器

Repeater{
    id: invoiceTab
    anchors.fill: parent
    model: invoice.tabmodel
    Button{
        width: 100
        height: parent.height
        text: test
        //text: display
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我使用displayrole 时,文本显示为2,但是当我test在 qml 中使用时,字符串显示正确

使用test角色

在此处输入图片说明

使用display角色时

在此处输入图片说明

2是从哪里来的?

pep*_*ppe 6

display 是 Button 的属性。

使用来自模型的数据时,请始终使用model.前缀来消除歧义 ( model.display)。