我想出了如何在QML中公开和绑定QAbstractListModel派生的listmodel的实例。
但我真正想做的是将一个对象暴露给QML并将一个QAbstractListModel派生的listmodel成员绑定为Q_PROPERTY。
我已经这样试过了:
class MyObject : public QObject
{
Q_OBJECT
Q_PROPERTY(MyListModel myListModel READ myListModel NOTIFY myListModelChanged)
public:
explicit MyObject(QObject *parent = 0);
MyListModel *myListModel();
signals:
void myListModelChanged();
public slots:
private:
MyListModel *m_myListModel;
};
MyObject::MyObject(QObject *parent) :
QObject(parent)
{
m_myListModel = new MyListModel(this);
}
MyListModel *MyObject::myListModel()
{
return m_myListModel;
}
class MyListModel : public QAbstractListModel {
Q_OBJECT
//...
//...
}
int main(int argc, char *argv[])
{
QGuiApplication a(argc, argv);
QQuickView *view = new QQuickView();
MyObject *myObject = new MyObject();
view->engine()->rootContext()->setContextProperty("myObject", myObject);
view->setSource(QUrl::fromLocalFile("main.qml"));
view->show();
return a.exec();
}
Rectangle {
width: 200
height: 200
//...
//...
ListView {
id: myListView
anchors.fill: parent
delegate: myDelegate
model: myObject.myListModel
}
}
但是我收到了编译错误:
E:\ Qt \ Qt5 \ 5.1.1 \ mingw48_32 \ include \ QtCore \ qglobal.h:946:错误:' QAbstractListModel& QAbstractListModel :: operator =(const QAbstractListModel&)'是私人的 Class& operator =(const Class&)Q_DECL_EQ_DELETE; ^
如何正确地做到这一点?
答案 0 :(得分:7)
Q_PROPERTY(MyListModel* myListModel READ myListModel CONSTANT)
由于您不替换模型本身,只是替换其内容,因此您不需要myListModelChanged()信号并将其标记为CONSTANT
。
你的getter已经有了正确的类型,虽然它应该是const:
MyListModel *MyObject::myListModel() const