Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access items of QStandardItemModel from QML

Tags:

c++

qt

qml

(EDITED) In original question I erroneously assumed that GridView natively use 2-dimensional model. Indeed, it takes a list of elements similarly as other QML views. To make the question and answers more understandable I changed given code slightly. Moreover, I added working soluton based on answers.

In main program I define an instance of QStandardItemModel:

QScopedPointer<QApplication> app(createApplication(argc, argv));
QmlApplicationViewer viewer;

QStandardItemModel* cppmodel = new QStandardItemModel();
for (int i=0; i<100; i++) {
    QStandardItem* item = new QStandardItem(QString("%1").arg(i,2,10,QChar('0')));
    cppmodel->appendRow(item);
}

Then, I register the model to QML with:

viewer.rootContext()->setContextProperty("cppModel",cppmodel);

QStandardItemModel is a table,isn't it? Then, how can I write a delegate to show items in a simple GridView:

    GridView {
        model: cppModel
        delegate: Rectangle {
            Text { text: ??? } //WHAT MUST BE USED HERE ???
        }
    }

Do I have to use named roles or can I just use properly created indices?

like image 997
meolic Avatar asked Aug 23 '12 12:08

meolic


2 Answers

Maybe It helps you:
Using QStandardItemModel in QML

Also you can try such code:

GridView {
   anchors.fill: parent
   model: cppModel
   delegate: Rectangle {
      Text {
         text: display;
      }
   }
}
like image 139
aleks_misyuk Avatar answered Oct 15 '22 10:10

aleks_misyuk


Since this question is 3 months old, you probably already have an answer, but to help others:

The short answer is to use:

datalist.currentIndex = index;

For example, with a ListView, this worked for me:

ListView {
    id: datalist
    model: cppModel
    delegate: Rectangle {
        Text {
             text: display;
        }
    }
}

...

MouseArea {
    anchors.fill: parent;
    onClicked: {
        datalist.currentIndex = index;
    }
}

This seemed like a thing everyone would need, however I didn't find it in any of the ListView examples.

like image 26
johnea Avatar answered Oct 15 '22 11:10

johnea