我有一个里面有几个ListElemts的ListModel。我希望这些元素在ListView中按节排序。当我运行以下命令时:
Page {
ListModel {
id: listModel
ListElement {
title: "life"
section: "a"
}
ListElement {
title: "universe"
section: "b"
}
ListElement {
title: "and everything"
section: "a"
}
}
ListView {
model: listModel
section {
property: 'section'
delegate: SectionHeader {
text: section
}
}
delegate: ListItem {
Label {
text: model.title
}
}
}
}
它提供了如下内容:
a
life
b
universe
a
and everything
但是,我希望它返回如下内容:
a
life
and everything
b
universe
我可以通过按照上面的顺序在模型中安排ListElements来手动实现这一点,但是,由于ListElements是动态的,所以这并不完美。如何确保ListElements按照我想要的方式自动排序?
发布于 2015-04-03 18:02:53
您可以定义一个函数sortModel
并在Component.onCompleted中进行调用
ListModel {
id: listModel
ListElement {
title: "life"
section: "a"
}
ListElement {
title: "universe"
section: "b"
}
ListElement {
title: "and everything"
section: "a"
}
function sortModel()
{
for(var i=0; i<count; i++)
{
for(var j=0; j<i; j++)
{
if(get(i).section == get(j).section)
move(i,j,1)
break
}
}
}
Component.onCompleted: sortModel()
}
发布于 2019-01-03 15:01:49
对于use部分,您必须创建Qstandart项目模型并设置sortRole(部分),然后将项目附加到qstandard项目和项目到模型。之后,您必须设置model-> sort (column)函数来对模型进行排序。
请看下面的代码:
c++代码如下:您有一个模型类,如下所示
#include <QStandardItemModel>
enum TypeContact
{
TitleRole = Qt::UserRole + 1,
SectionRole = Qt::UserRole + 2,
};
class MyModel : public QStandardItemModel
{
Q_OBJECT
public:
MyModel(QObject *parent = 0)
: QStandardItemModel(parent)
{
}
protected:
QHash<int, QByteArray> roleNames() const
{
QHash<int, QByteArray> m_roles;
m_roles[TitleRole] = "titleRole";
m_roles[SectionRole] = "sectionRole";
return m_roles;
}
};
在你的另一个类中,你想把你的数据追加到模型中,写道:
//in .h file
QStandardItemModel *model {nullptr};
//.in .cpp file
model = new MyModel(this);
model->clear();
model->setSortRole(sectionRole);
然后插入你的数据。
QStandardItem *item = new QStandardItem;
item->setData( "life", titleRole);
item->setData( "a", sectioRole);
model->appedRow(item);
QStandardItem *item2 = new QStandardItem;
item2->setData( "universal", titleRole);
item2->setData( "b", sectioRole);
model->appedRow(item2);
QStandardItem *item3 = new QStandardItem;
item3->setData( "and every think", titleRole);
item3->setData( "a", sectioRole);
model->appedRow(item3);
并像这样排序模型:
model->sort(0);
qml代码将为:
ListView {
anchors.fill: parent
model: MyModel
delegate: Label {
text: titleRole
width: 100
height: 50
}
section.property: "sectionRole"
section.criteria: ViewSection.FullString
section.delegate: Label {
text: section
font.bold: true
font.pixelSize: 25
}
}
我没有准确地测试它,但它一定是工作。如果您搜索Q标准项目模型,以及如何将其附加到model并将其设置为model,您就会确切地知道您必须做什么。但是这里的setSortRole()和sort()是很重要的。
谢谢
https://stackoverflow.com/questions/29429710
复制相似问题