简体   繁体   中英

How to setModel for QListWidget

Is there any way to setModel for QListWidget? I am getting AttributeError: QListWidget.setModel is a private method on this:

class Model(QtCore.QAbstractListModel):
    def __init__(self):
        QtCore.QAbstractListModel.__init__(self)
        self.items=[]
    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.items)
    def flags(self,index):
        return QtCore.Qt.ItemIsEditable

view=QtGui.QListWidget()

viewModel=Model()
view.setModel(viewModel)

I don't think so you can set model for QListWidget. Because QListWidget has its own model. But you can use QListView and you can set your own model to QListView

I simply would like to complete @Achayan's answer: if you have a look at Qt's documentation, you can find a very good tutorial explaining precisely the difference between

  • implementation via standard widgets
  • implementation via Model/View

In the first case, the standard widgets own a version of the data , which can seem easier to do and manage at first glance, but can lead to problem of synchronization . Indeed, if the widget itself (which is a view) owns its own version of the data, you have to be sure that this data is synchronized with the database. And what's more, if you have, let's say 2 or 3 others widgets of the same model (example: a table, a list and a combobox representing the same entity), therefore you have four versions of the data...

The second one is better if you want a more decoupled and flexible implementation: the model is really "simply" a view, and does not own any data. He simply interacts with the model, which therefore has to implement a given interface ( QAbstractItemModel ).

In your case: QListWidget is the "standard widget", and QListView is the view of the Model/View implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM