从QML访问QStandardItemModel的项

从QML访问QStandardItemModel的项

本文介绍了从QML访问QStandardItemModel的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(EDITED)在原始问题我错误地假设GridView本机使用2维模型。实际上,它需要一个列表的元素类似于其他QML
视图。为了使问题和答案更容易理解,我改变了给定代码



在主程序中,我定义了一个QStandardItemModel的实例:

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

QStandardItemModel * cppmodel = new QStandardItemModel();
for(int i = 0; i QStandardItem * item = new QStandardItem(QString(%1)。arg(i,2,10,QChar('0' )));
cppmodel-> appendRow(item);然后,我使用以下命令将模型注册到QML:



$ b

 $ b 

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

QStandardItemModel是一个表,不是吗?然后,我如何写一个委托给
在一个简单的GridView中显示项目:

  GridView {
model:cppModel
delegate:Rectangle {
Text {text:? } //这里必须使用什么?
}
}

我必须使用命名角色吗?


解决方案

也许它可以帮助你:



也可以尝试这样的代码:

  GridView {
anchors.fill:parent
model:cppModel
delegate:Rectangle {
Text {
text:display;
}
}
}


(EDITED) In original question I erroneously assumed that GridView natively use 2-dimensional model. Indeed, it takes a list of elements similarly as other QMLviews. To make the question and answers more understandable I changed given codeslightly. 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 toshow 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?

解决方案

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;
      }
   }
}

这篇关于从QML访问QStandardItemModel的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:17