Important: Please read the Qt Code of Conduct -

problem creating QAbstractItemModel

  • Hi all -

    This is only my 2nd time working in the model/view world. I was trying to use the code from my 1st time as a, well, you know...model.

    I want to populate a model with data I receive from a TCP message. I have a class containing the model:


    class ModelApScan : public QObject
        QAbstractItemModel *m_model;    // the main model
        explicit ModelApScan(QObject *parent = Q_NULLPTR);
    public slots:
        void update(Message *msg, vector<string> &keys);


    ModelApScan::ModelApScan(QObject *parent) : QObject(parent), m_model(new QStandardItemModel(this))
        m_model->insertColumns(0, AP_TABLE_NBR_COLUMNS);
        m_model->setHeaderData(AP_TABLE_COLUMN_MACADDR, Qt::Horizontal, tr("MAC Address"), Qt::DisplayRole);
        m_model->setHeaderData(AP_TABLE_COLUMN_SSID, Qt::Horizontal, tr("SSID"), Qt::DisplayRole);
        m_model->setHeaderData(AP_TABLE_COLUMN_RSSI, Qt::Horizontal, tr("RSSI"), Qt::DisplayRole);
    void ModelApScan::update(Message *msg, vector<string> &keys)
        int row;
        int rowCnt = m_model->rowCount();

    This is, as far as I can see, verbatim from my 1st model. But, I get a segfault on the call to rowCount() in update(). Can anyone see what I'm doing wrong?


  • @mzimmers
    I've implemented your snippet and everything is working fine.

    Can you share with us an extended snippet ? Maybe, the problem is in way that you insert the Items in the Model.

  • Lifetime Qt Champion

    @mzimmers said in problem creating QAbstractItemModel:

    I get a segfault on the call to rowCount()

    If you get a segfault there then it means m_model is invalid pointer.
    Do you delete m_model somewhere?

  • @KillerSmath hi - I'm not inserting any items yet. My model is empty when I make that call.

    @jsulm no, I'm not deleting it, stepping through the debugger, I just realized that my c'tor isn't being called. That's really odd...don't know what to make of that, though it does explain why the call to rowCount() blows up.

  • Lifetime Qt Champion


    Where are you creating the instance of ModelApScan ?
    Are you sure it's still valid when calling update ?

  • Bingo...I wasn't creating it. I created the pointer but never invoked the c'tor from the parent. Now corrected:

    EditDialog::EditDialog(DeviceModel *d, QModelIndex *qmi, Worker *pWorker, QWidget *parent) :
        ui(new Ui::EditDialog),
           // create the model that holds the results of the AP scan.
        m_modelApScan = new ModelApScan();

    Amazing the brain-dead mistakes one can make when distracted...thanks for the help.

  • Lifetime Qt Champion

    Side note (partly aesthetics), you can keep m_modelApScan in the initialiser list of your EditDialog class constructor.

Log in to reply