13

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.

Metal Wing
  • 1,065
  • 2
  • 17
  • 40

2 Answers2

14

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;
xander
  • 1,780
  • 9
  • 16
  • 1
    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! – Metal Wing Feb 27 '17 at 14:20
  • 1
    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`? – xander Feb 27 '17 at 14:24
  • @MetalWing I've added a short example to my answer, but it depends what you actually use as a model I have no clue. :) – xander Feb 27 '17 at 14:30
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).

Toby Speight
  • 27,591
  • 48
  • 66
  • 103