Editable List version of qt\examples\objectlistmodel
-
Hello I tried to make the qt\examples\objectlistmodel objectlist editable, by this meaning: giving the user the chance to change the values of the QList<QObject*> elements from the UI.
Inside the ListView delegate I substituted a TextEdit{} instead of Text{}. But the only way I found to get back the modified values in QList<QObject*> was to add an int index field inside the single QObject. I had tried with
onEditingFinished : parent.name=text
but it wouldn't work (the displayed values would change inside the delegate but it would not feedback to the original C++ list).
I had tried with
onEditingFinished : listview.model[listview.currentIndex].name=text
but it would not work because listview.currentIndex is always 0.
I will paste now the "working code" which I dislike because I would like to access and edit the single QList element from inside the delegate without having to store inside the element a redundant list index used by the delegate to perform that job.
Not only it is redundant but also needs coherent handling when the list is added or deleted elements.view.qml import QtQuick import QtQuick.Controls //![0] ListView { id: listview width: 200; height: 320 model: dataList ScrollBar.vertical: ScrollBar { } delegate: Rectangle { width: listview.width; height: 25 required property string name required property int indx //this is the element added!! required color TextEdit { text: parent.name onEditingFinished: { //parent.name=text //this doesn't work (the following line works) listview.model[parent.indx].name=text; } } } } //![0]
and here is the C++ code:
int main(int argc, char ** argv) { QGuiApplication app(argc, argv); const QStringList colorList = {"red", "green", "blue", "yellow"}; const QStringList moduleList = {"Core", "GUI", "Multimedia", "Multimedia Widgets", "Network", "QML", "Quick", "Quick Controls", "Quick Dialogs", "Quick Layouts", "Quick Test", "SQL", "Widgets", "3D", "Android Extras", "Bluetooth", "Concurrent", "D-Bus", "Gamepad", "Graphical Effects", "Help", "Image Formats", "Location", "Mac Extras", "NFC", "OpenGL", "Platform Headers", "Positioning", "Print Support", "Purchasing", "Quick Extras", "Quick Timeline", "Quick Widgets", "Remote Objects", "Script", "SCXML", "Script Tools", "Sensors", "Serial Bus", "Serial Port", "Speech", "SVG", "UI Tools", "WebEngine", "WebSockets", "WebView", "Windows Extras", "XML", "XML Patterns", "Charts", "Network Authorization", "Virtual Keyboard", "Quick 3D", "Quick WebGL"}; QList<QObject *> dataList; int i = 0; for (const QString& module : moduleList) { dataList.append(new DataObject("Qt " + module, colorList.at(rand() % colorList.length()), i++)); } QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); view.engine()->rootContext()->setContextProperty("dataList", QVariant::fromValue(dataList)); //![0] view.setSource(QUrl("qrc:/objectlistmodel/view.qml")); view.show(); return app.exec(); }