我试图严格地将数据(在C ++中)与可视化(QML中的列表)分开。在模型方面,数据存储在C ++类(Data.cpp)的实例中,指向这些实例的指针由另一个C ++类(Parser.cpp)排列在两个列表(completeList和selectedList)中。这两个列表应以QML显示,但有以下限制:
感谢ksimons,I found a way to do half of it,但我无法弄清楚其余部分。这是我到目前为止所得到的:
Data.h
class Data : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
public:
Data(const QString &n) : _name(n) { }
QString name() const { return _name; }
void setName(const QString &n) {
if (_name == n)
return;
_name = n;
emit nameChanged(n);
}
signals:
void nameChanged(const QString &n);
private:
QString _name;
};
Parser.h
class Parser : public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<Data> completeList READ completeList CONSTANT)
Q_PROPERTY(QQmlListProperty<Data> selectedList READ selectedList CONSTANT)
public:
Parser(QObject *parent = 0) {
Data* d1 = new Data(QStringLiteral("a1"));
Data* d2 = new Data(QStringLiteral("a2"));
Data* d3 = new Data(QStringLiteral("a3"));
Data* d4 = new Data(QStringLiteral("b1"));
Data* d5 = new Data(QStringLiteral("b2"));
_completeList.append(d1);
_completeList.append(d2);
_completeList.append(d3);
_completeList.append(d4);
_completeList.append(d5);
_selectedList.append(d1);
_selectedList.append(d4);
}
QQmlListProperty<Data> completeList() {
return QQmlListProperty<Data>(this, _completeList);
}
QQmlListProperty<Data> selectedList() {
return QQmlListProperty<Data>(this, _selectedList);
}
private:
QList<Data*> _completedList;
QList<Data*> _selectedList;
};
QML部分:
ListView
{
id: startsWithA
anchors.fill: parent
delegate: delegateItem
}
ListView
{
id: startsWithB
anchors.fill: parent
delegate: delegateItem
}
ListView
{
id: selectedData
anchors.fill: parent
delegate: delegateItem
}
Item
{
id: delegateItem
height: 30
width: parent.width
Text { text: name }
MouseArea { //change name of corresponding Data and other views accordingly
anchors.fill: parent
onClicked: model.name = "newName";} //does not work
MouseArea { //add to selectedList in Parser
anchors.fill: parent
onClicked: ?????? }
}
Component.onCompleted:
{
selectedData.model = parser.seletedList;
var listAll = parser.completeList;
var listA, listB;
for(var i=0; i<listAll.length; i++)
{
if(listAll[i].name.charAt(0) == 'a')
{
//changing values in startsWithA does not affect anything else with that :(
listA.append(listAll[i]);
}
else if(listAll[i].name.charAt(0) == 'b')
{
//changing values in startsWithB does not affect anything else with that :(
listB.append(listAll[i]);
}
//...
}
startsWithA.model = listA;
startsWithB.model = listB;
//...
}
我希望这个问题不具体,有人可以帮助我。提前谢谢。