Creating a QModelIndex

Metal Wing picture Metal Wing · Feb 27, 2017 · Viewed 22.2k times · Source

I have spent the last week struggling to create a QModelIndex given a row and a column.

Alternatively, I would settle for changing the value of row() in an already existing QModelIndex.

Any help would be appreciated.

Edit:

QModelIndex nIndex = QAbstractItemModel::createIndex(1, 2);
int b = nIndex.row();
qInfo() << "b" << b;

Fails with error:

cannot call member function ‘QModelIndex QAbstractItemModel::createIndex(int, int, void*) const’ without object
         QModelIndex nIndex = QAbstractItemModel::createIndex(1, 2);
                                                                  ^

The goal at hand is this:

I have a function:

void MyClass::doStuff(QModelIndex index)

Inside that class, I essentially do the following:

if (index.column() != 1)
{
    int a=index.row();
}

So my goal is to call that function from a different class and pass it a QModelIndex, but for that index to have been created with a row/column I specify.

Answer

xander picture xander · Feb 27, 2017

I'm not sure this is what you want, but you can just create a QModelIndex with the method QAbstractItemModel::index(row, column) ( http://doc.qt.io/qt-5/qabstractitemmodel.html#index )!? On the other hand that seems to be to simple for you to struggle with it for so long, maybe explain a little bit more.

Example:

QAbstractTableModel *model = ...;

// then you can do something like
QModelIndex nIndex = model->index(1,2);
int b = nIndex.row();
qInfo() << "b" << b;