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()
Related posts
- PyQt: How to pass arguments while emitting a signal — posted 2008-01-29
- PyQt4 QItemDelegate example with QListView and QAbstractListModel — posted 2008-01-23
- How to install pyqt4 on ubuntu linux — posted 2008-01-15
- Python PyQt Tab Completion example — posted 2008-01-04
- How to capture the Tab key press event with PyQt 4.3 — posted 2008-01-03
Comments
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.
Just nitpicking, but shouldn't you be calling QAbstractListModel's and not QAbstractTableModel's __init__ method in the list models own __init__ method?
Magnus, You are right. It must have been a copy/paste error. Thank you for the correction. I have updated the code above.
Thankyou for the example. The documentation is a bit opaque, I prefer to see it working first, then figure out how it works..
Im getting error in DisplayRole, no attribute
Thanks for sharing your knowledge, Qt is a very large library with a very good documentation available only for C++.
but it lacks some specials PyQt methods like toPyObject(), and sometimes i find that in C++ there is a public method to access and set data but in PyQt i just have to use the dot assignment.
I always waste time trying to figure out if a method works the way it does in C++.
Anyway Qt stays the best!!!
Thank you very Much!!!
disqus:2115784754