//.h
class Model : public QAbstractListModel
{
Q_OBJECT
struct ModelItem {
QString name;
int age;
};
enum {NAME=Qt::UserRole+1, AGE};
public:
explicit Model(QObject *parent = 0);
int rowCount(const QModelIndex & parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
QHash<int, QByteArray> roleNames() const;
private:
QList<ModelItem> list;
};
//.cpp
Model::Model(QObject *parent) :
QAbstractListModel(parent)
{
ModelItem item;
item.name = "aaaa";
item.age = 34;
list.push_back(item);
item.name = "bbbbb";
item.age = 33;
list.push_back(item);
item.name = "ccccc";
item.age = 55;
list.push_back(item);
for(int i=0; i<100; i++)
{
item.name = QString::number(i);
item.age = i;
list.push_back(item);
}
}
int Model::rowCount(const QModelIndex &) const
{
return list.size();
}
QVariant Model::data(const QModelIndex &index, int role) const
{
int i = index.row();
if (i < 0 || i >= list.size())
return QVariant();
if (role == NAME)
return list[i].name;
if (role==AGE)
return list[i].age;
//if (role==Qt::DisplayRole)
// return list[i].name + " ("+ QString::number(list[i].age) +")";
return QVariant();
}
QHash<int, QByteArray> Model::roleNames() const
{
QHash<int, QByteArray> r =QAbstractListModel::roleNames();
r[NAME] = "name";
r[AGE] = "age";
return r;
}
//qml
Window {
visible: true
width: 480
height: 360
title: qsTr("Hello World")
id : root
objectName: "root"
property int currentIndex : 0
ListView {
id : listview
anchors.fill: parent
model: modcpp
delegate: id_delegate
currentIndex: root.currentIndex
}
Component{
id : id_delegate
Item {
id : wrapper
width: parent.width
height: 57
Column{
width: parent.width
height: parent.height
Row{
width: parent.width
height: parent.height - 1
Rectangle{
id :id_icon
width : parent.width / 2
height: parent.height
color: "transparent"
Text {
anchors.fill: parent
text: "名字:" + name
color: currentIndex===index ? "red" : "black"
font.pixelSize: currentIndex===index ? 22 : 18
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignVCenter
}
MouseArea{
anchors.fill: parent
onClicked: {
root.currentIndex = index
}
}
}
Rectangle{
width : parent.width / 2
height: parent.height
color: "transparent"
Text {
anchors.fill: parent
text: "年龄:" + age
color: currentIndex===index ? "red" : "black"
font.pixelSize: currentIndex===index ? 22 : 18
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
}
MouseArea{
anchors.fill: parent
onClicked: {
root.currentIndex = index
}
}
}
}
Rectangle{
width: parent.width
height: 1
color: "#6E7489"
}
}
}
}
}
运行测试,效果如下:
资源链接:点击跳转