I have a simple list:
mylist = ["foo", "bar", "baz"]
and a QtTableWidget with 1 column. I would like to keep the data in mylist in sync with that in the QtTableWidget, including allowing drag-and-drop reordering (i.e., the user can do that, and mylist gets updated) and programmatic changes (i.e., I update mylist and the table gets updated).
What is the right way to do this?
Note that in general there’s no way in Qt/C++ proper to link a generic data structure with a view. Models are such instrumented data structures that allow trivial linking with views — generic lists, like say
QStringListcan’t be used like that.In Python it should be possible to inject attributes into an existing instance of any list to turn it into a model that notifies its views of changes done to it. I don’t know if any Qt-to-Python bridges do that sort of a thing, I can only give C++ perspective on this. Someone who knows PyQt or PySide is welcome to chime in and edit as appropriate.
Use a
QStringListModelfor the model. Enable drag-drop reordering on the view as follows:My other answer has a full example that uses the convenience widget
QListWidgetwith its buit-in model. That may be better as a starting point, and for lists that can be reasonably manipulated with a mouse, it’s a good choice. Generally if a model has 100s of items, it can’t be readily manipulated with just a mouse without a way of doing real-time finds or pruning of some sort — scrolling so many items is a usability nightmare. So don’t do it.Qt’s documentation would be a good plate to start learning. Read about the model/view framework. Then look at
QStringListModeland your chosen view, sayQTableVieworQListView.