PyQT ModelView example

692 views
Skip to first unread message

thirstydevil

unread,
May 29, 2009, 7:40:39 PM5/29/09
to python_inside_maya
Tonight I tried to play with QT's QModel concept. It had stumped me
for quite sometime at work today. I couldn't rest untill I had
understood the basics. I'm not sure if this will be usefull to the
hoi polloi but some may find it useful.

Anyways, heres a listView using a QDirModel for reference.
Oh, and for those that are python/Qt gurus please comment if I'm doing
this the wrong way.

-Cheers
Dave

## ----------------------------------------------

from PyQt4 import QtCore, QtGui
import sys
import os

class UI(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)

self.setWindowTitle('listView ModelView Example')
self.listView = MyListView()
self.upButton = QtGui.QPushButton()
self.upButton.setText("Up")

grid = QtGui.QGridLayout()
grid.addWidget(self.upButton)
grid.addWidget(self.listView)

self.setLayout(grid)

self.resize(300, 150)

items = self.listView.getModelItemCollection()
print self.listView.DirModel.getData(items)

self.connect(self.upButton, QtCore.SIGNAL("clicked()"),
self._GoUp)

def _GoUp(self):
path = self.listView.DirModel.filePath(self.listView.rootIndex
())
self.listView.setRootIndex(self.listView.DirModel.index
( os.path.dirname(str(path))))

@staticmethod
def Display():
app = QtGui.QApplication(sys.argv)
win = UI()
win.show()
sys.exit(app.exec_())

class MyDirModel(QtGui.QDirModel):
'''
SubClass of QtGui.QDirmodel
'''
def __init__(self):
super(MyDirModel, self).__init__()

def getData(self, ModelIndex):
'''
Using QModelIndex I can get data via the data() method or
via any other method that suport a QModelIndex
'''
paths = []
if isinstance(ModelIndex, list):
for items in ModelIndex:
#print self.data(items).toString()
paths.append(self.filePath(items))
return paths
else:
raise ValueError("getData() requires a list
(QtGui.QModelIndexs)")

class MyListView(QtGui.QListView):
'''
SubClass of QtGui.QListView
'''

def __init__(self, parent = None):
super(MyListView, self).__init__(parent)
self.DirModel = MyDirModel()
self.setModel(self.DirModel) # we have to set the listView to
use this DirModel
self.setRootIndex(self.DirModel.index("c://")) # set the
deafault to load to c:\

self.connect(self, QtCore.SIGNAL("doubleClicked
(QModelIndex)"), self._DoubleClicked)

def getModelItemCollection(self):
'''
From this list get the QModelIndex that we set
with .setRootIndex
Using QModelIndex and DirModel we can get all the elements at
that Index
'''
ModelIndex = self.rootIndex()
ModelIndexCollection = []
for i in range(0, self.DirModel.rowCount(ModelIndex)):
ModelIndexCollection.append(ModelIndex.child(i,0))
return ModelIndexCollection

def _DoubleClicked(self):
if self.DirModel.isDir(self.currentIndex()):
path = self.DirModel.filePath(self.currentIndex())
self.setRootIndex(self.DirModel.index(path))
items = self.getModelItemCollection()
print self.DirModel.getData(items)

if __name__ == "__main__":
UI.Display()

Chad Dombrova

unread,
May 30, 2009, 12:49:25 PM5/30/09
to python_in...@googlegroups.com
hey thanks for the example code!
i messed around with the QModelView when trying to create an iTunes-
style navigation widget, but i remember having a lot of trouble
getting it to work. as i remember, a big part of the problem was
getting it to support the notion of the "All" item that appears at the
top of every column in iTunes. this is going on much-faded memory,
but perhaps it had something to do with QViewModel working more like a
tree, whereas iTunes behaves as a filtering system, where each
column's filter can be applied or not (the "not" being the "All"
item). after having mastered QModelView, do you have any insight into
this? do you know if QModelView could handle the slightly simpler --
and more tree-like -- case of a Finder-style column-based navigation?

-chad

thirstydevil

unread,
May 30, 2009, 4:38:52 PM5/30/09
to python_inside_maya
"after having mastered QModelView"
:) not quite yet, but maybe in a few months. I'm writing a "Maya Asset
Finder" at work which will display pipeline related tools based on the
selection or mode the user manualy chooses. With other Nview style
previews of textures ect. We did toy with the idea of meta tags via a
back end dB but meta filtering and who has access to add tags etc
caused us a pipeline headache.

I've not used Itunes but I am downloading now :). I would imagine
that the filtering is done by itunes dB somewhere? When the file is
scanned it's mp3 tags are added to the root data base somehow. I
suspose that you could use QSqlRelationalTableModel to set/get the
filter dB relationships. You would then implement a custom
QTreeViewWidget designed to display your custom tree. Firing of
Signals to your treeView/listView or tableView that uses
QSqlTableModel. It's a lot more advanced than I currently am. so
sorry :(

Python Qt ramble...
As I get more into PyQt I find that I'm learning python a lot better.
I've come from a animator/environment artist background and learnt mel
as a way to batch basic tasks. Then when I started learning python I
found I was programming in a Mel style. OO programming was a mistery
to me. I got alittle better but it wasn't untill I decided to learn
PyQt that reading the OO api forced me to think differently. I even
split my UI designs in Qt to seperate UI's and parnet them in to main
UI. So for anyone finding OO programming tuff. You have to use a OO
api before you start to get it.

laters
-Dave

Ben Chess

unread,
Jun 1, 2009, 11:52:48 AM6/1/09
to python_in...@googlegroups.com
PyQt comes with a file called "modeltest.py" in the contrib directory
that is a huge help in developing & debugging your custom
QAbstractItemModel. It's tricky to write one correctly, and
modeltest.py runs it through a gauntlet of asserts to ensure that
everything is behaving as it should.

Ben
Reply all
Reply to author
Forward
0 new messages