Using MVC's insertRow() with custom subclassed QStandardItem
-
Greetings!
I'm making a project using Python 3.9 / PyQt 5. In it, I'm using the model / view approach to display some data in a QTreeView. Currently I'm trying to implement a method for moving items in a tree up and down (without drag and drop, but by clicking specific buttons). For some mysterious reason, there's no dedicated function for it in PyQt, so I'm doing it from scratch, and for that I need the insertRow() function.
Apparently it takes two arguments: an int for the row it must insert after, and a list of item objects. Thing is, in my project, I'm using custom item class StandardItem subclassing QStandardItem. It worked just fine with methods like appendRow() which use identical syntax, but for some reason, when I do it with insertRow(), it crashes the app with "TypeError: index 0 has type 'StandardItem' but 'QStandardItem' is expected". The fragment of code I'm using it in goes like this - https://pastebin.com/ghnG0zSz Lines 35 and 39 throw this error. What am I doing wrong? -
@Sinarch
Hello and welcome.Start by scrapping (i.e. not using) all your code for deleting/copying/moving items, selection models, etc. Just create a list of some
StandardItem
s and compareinsertRow()
againstappendRow()
.When you get it working: instead of all your copying of items and deleting rows, try QList<QStandardItem *> QStandardItemModel::takeRow(int row) for passing to those two.
You can see the C++ source code for both of these methods in https://code.woboq.org/qt5/qtbase/src/gui/itemmodels/qstandarditemmodel.cpp.html (where you can click on function calls to follow the code). I can't spot why
appendRow()
succeeds whileinsertRow()
fails.If you are still stuck: the error message implies it does not like the
StandardItem
s in your row, for some reason. If you have to, why not insert an empty row, which hopefully it won't object to, and then set the columns in that row from your data? -
@Sinarch said in Using MVC's insertRow() with custom subclassed QStandardItem:
Currently I'm trying to implement a method for moving items in a tree up and down (without drag and drop, but by clicking specific buttons). [..] I'm doing it from scratch, and for that I need the insertRow() function.
I don't get this. What you need is to either reimplement
moveRows
of the model or (easier to implement if performance is not a bottleneck) just calllayoutAboutToBeChanged
, do your reordering and then calllayoutChanged