Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QAbstractItemModel



  • Hello all,
    I'm trying to remember how to use a QAbstractItemModel with a QListView.

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->lvGroups->setModel(&m_groupModel);
    }
    ...
    void MainWindow::on_actionNew_Group_triggered()
    {
        GroupData grp(-1, "New Group");
        m_groupModel.addGroup(grp);
    }
    ...
    void GroupModel::addGroup(const GroupData &data)
    {
        qDebug() << "GroupModel::addGroup";
        beginInsertRows(QModelIndex(), m_groups.size(), m_groups.size());
        qDebug() << "appending group data";
        m_groups.append(data);
        qDebug() << "appended";
        endInsertRows();
    }
    ...
    QVariant GroupModel::data(const QModelIndex &index, int role) const
    {
        qDebug() << "GroupModel::data" << index.row();
        Q_UNUSED(role);
        if (!index.isValid())
            return QVariant();
        return m_groups.at(index.row()).name();
    }
    

    I don't see the group name in the list view, nor the appropriate qDebug() message in data(). I do see qDebug messages from addGroup().

    I must be missing something stupid. Could somebody help me out, please?


  • Lifetime Qt Champion

    Hi,

    That's because you are returning the same string for every role. You should be more selective. Return that string only for the DisplayRole and EditRole.



  • @SGaist
    Thanks.
    But data() never gets called.


  • Lifetime Qt Champion

    Wrong model sizes ?

    Based on the code you shared, it's only guesses.

    Are you sure you correctly implemented all the required method ?

    You can check your model with the Qt model tester.



  • Bingo. Wrong model sizes. The QItemModel wizard puts logic that isn't appropriate for a QListView. If one isn't careful they will not implement rowCount() and columnCount() correctly. Pretty subtle mistake, actually.
    First of all, it will generate a compiler warning. Second, while the !parent.isValid() should be used to return the model size, return 0 makes me think it should always return 0. For QListViews, it should return the model size.
    The wizard could be more helpful, IMO.

    Mo' coffee.

    int RestaurantModel::rowCount(const QModelIndex &parent) const
    {
        if (!parent.isValid())
            return 0;
    
        // FIXME: Implement me!
    }
    
    int RestaurantModel::columnCount(const QModelIndex &parent) const
    {
        if (!parent.isValid())
            return 0;
    
        // FIXME: Implement me!
    }
    
    

Log in to reply