[SOLVED] ListView drag and drop, data model exposed from C++
-
Hi
This is a great example of how to implement drag and drop in QML:
http://developer.qt.nokia.com/wiki/Drag_and_Drop_within_a_GridViewWould it be also possible to implement similar feature if I use the data model exposed from C++
( context->setContextProperty("listItems", QVariant::fromValue(listItems)) ),
and not the data model defined in QML (via ListModel)? -
Yes. You need to implement some methods marked as Q_INVOKABLE to move elements, but I'm sure it not too difficult.
-
Ok, but if you look at the example code, "icons.move(newIndex, newIndex = index, 1)" is used in QML javascript.
icons is defined as: " model: WidgetModel { id: icons }"
in my case I'm using model exposed from C++, so it's: "model: myModel"
And there I can not use QML javascript code "myModel.move() to move the item", or maybe I can?
-
you can use "myModel.move()" from js if you have move() method marked as Q_INVOKABLE or slot.
-
Don't forget to mark your own threads which you think are solved with "[solved]" in title.
-
Hello!
I got exactly the same issue as borut123, and from your explanations I understand:
To be able to use myModel.move() in QML I need to implement in C++ move() by using Q_INVOKABLE.But:
- After reading QML and C++ documentation, Q_INVOKABLE is needed to create NEW methods in C++ (not previously existing in QML), then make them visible to QML and next use them in QML.
- move() method is a property ALREADY defined in QML as ListModel::move ( int from, int to, int n ).
The question is:
how exactly I have to use Q_INVOKABLE with move() to enable usage of myModel.move() in QML? Because I should need to declare in the C++ model class? Then: Is it needed to reimplement move() in .cpp also? -
You need to implement QAbstractListModel, and then send the instance of this model to QML.
C++ header file code snippet:
@class YourObject : public QAbstractListModel {
Q_OBJECT
public:
int rowCount(const QModelIndex & parent = QModelIndex()) const;
Q_INVOKABLE void move(int from, int to, int count);
Q_INVOKABLE YourObject* get(int i) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;@
I hope this helps you a little bit.