Creating a QModelIndex
Asked Answered
S

2

15

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.

Shipboard answered 27/2, 2017 at 14:0 Comment(0)
B
15

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;
Bloodshot answered 27/2, 2017 at 14:4 Comment(3)
I think the real struggle comes from being new to Qt. I think what you've said is what I want and tried; however, the struggled continues. I've updates my initial post to have some more info. Thank you!Shipboard
I changed my answer, the first link was wrong sorry, you can use the QAbstractItemModel::index (not createIndex, that is protected), and if you're new you can't just call it like that it's not static. You need a valid "data model" where you store the data and on that call the index method. I guess you have a model somewhere, what else is the point of getting a QModelIndex?Bloodshot
@MetalWing I've added a short example to my answer, but it depends what you actually use as a model I have no clue. :)Bloodshot
P
9

You can get a new index from the appropriate model, using its index() method.

If you already have an index from the model, with the same parent as your desired index, then you can get another index using the sibling() method of that index:

void MyClass::doStuff(const QModelIndex& index)
{
    // get the value at row zero, same column
    const QModelIndex header = index.sibling(0, index.column());
}

The index itself is immutable once created - you can't change its row, column or parent (other than by invalidating it with changes to the model behind its back).

Phantasmal answered 27/2, 2017 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.