How to update model view if data changed?

If I click any row in the list, my data will be modified (wired setup just to replicate the external data update case). How to load updated data in my widget?
Probably I need to use layoutChanged signal, but I had no luck with this.

from PySide2 import QtCore, QtWidgets

class Project:
    def __init__(self, project_name):
        self.id = None
        self.name = project_name
        self.maya = ''
        self.description = ''

class Model(QtCore.QAbstractListModel):
    def __init__(self, data=[], parent=None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self._data = data

    def rowCount(self, parent):
        return len(self._data)

    def data(self, index, role):

        if not index.isValid():
            return

        row = index.row()
        value = self._data[row]

        if role == QtCore.Qt.DisplayRole:
            return value.name
        if role == QtCore.Qt.UserRole:
            return value

app = QtWidgets.QApplication([])

def update_data():

    global data
    data = [Project('Strawberry')]

data = [Project('Apple'), Project('Banana')]
model = Model(data)

list = QtWidgets.QListView()
list.setModel(model)
list.clicked.connect(update_data)
list.show()

app.exec_()

Model.layoutChanged.emit()”

Here’s a nice tutorial on using PyQt’s ModelView which uses it

Thanks, nice article, will go through it definitely…

But with my current setup, when I don`t modify data in Model class, where should I define this Model.layoutChanged.emit()?

model = Model(data)
model.layoutChanged.emit()

Did not work…

Ok, got it working. The issue was that I did not modify my data in update_data() function, I created a new one. So:

def update_data():

    global model
    global data

    model.layoutAboutToBeChanged.emit()
    data.append(Project('Peaches'))
    model.layoutChanged.emit()
1 Like