SaltyCrane Blog — Notes on JavaScript and web development

PyQt 4.3 Simple QAbstractListModel/ QlistView example

import sys
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

#################################################################### 
def main(): 
    app = QApplication(sys.argv) 
    w = MyWindow() 
    w.show() 
    sys.exit(app.exec_()) 

#################################################################### 
class MyWindow(QWidget): 
    def __init__(self, *args): 
        QWidget.__init__(self, *args) 

        # create table
        list_data = [1,2,3,4]
        lm = MyListModel(list_data, self)
        lv = QListView()
        lv.setModel(lm)

        # layout
        layout = QVBoxLayout()
        layout.addWidget(lv) 
        self.setLayout(layout)

#################################################################### 
class MyListModel(QAbstractListModel): 
    def __init__(self, datain, parent=None, *args): 
        """ datain: a list where each item is a row
        """
        QAbstractListModel.__init__(self, parent, *args) 
        self.listdata = datain
 
    def rowCount(self, parent=QModelIndex()): 
        return len(self.listdata) 
 
    def data(self, index, role): 
        if index.isValid() and role == Qt.DisplayRole:
            return QVariant(self.listdata[index.row()])
        else: 
            return QVariant()

####################################################################
if __name__ == "__main__": 
    main()

Comments


#1 waseem commented on :

hello, i read this post and it's quite helpful i am still having problem in my application on how to link the qlistview with qfiledailoug, how can i made them talk to each other, my UI was designed using qt designer 4.4 then converted to python classes but since then i am stuck on the linking part of the functions. Any idea on how to link the Qfiledailoug that will browse my system data and try to import them on the Qlistview.


#2 Magnus Österlind commented on :

Just nitpicking, but shouldn't you be calling QAbstractListModel's and not QAbstractTableModel's __init__ method in the list models own __init__ method?


#3 Eliot commented on :

Magnus, You are right. It must have been a copy/paste error. Thank you for the correction. I have updated the code above.


#4 ian Rees commented on :

Thankyou for the example. The documentation is a bit opaque, I prefer to see it working first, then figure out how it works..


#5 fille commented on :

Im getting error in DisplayRole, no attribute