开发者

PyQt and ListModel

How can I fill a data list in a data listmodel with the content of a given path?

Here is what I'm trying to do :

class TestListModel(QAbstractListModel):
    def __init__(self, parent=None):
        QAbstractListModel.__init__(self, parent)
        self.testnames = []

    def load_docfiles(self):
        cfg = Config()
        for filename in glob.glob(os.path.join(cfg.test_path, 'test_*.rst'开发者_运维问答)):
            self.testnames = os.path.basename(filename)[5:-4]
            filepath = os.path.abspath(filename)
            print "load docfile", str(self.testnames)
        return str(self.testnames)

    def rowCount(self, index):
        return len(self.testnames)

    def data(self, index, role): 
        if role == Qt.DisplayRole:
            cfg = Config()
            for filename in glob.glob(os.path.join(cfg.test_path, 'test_*.rst')):
                self.testnames = os.path.basename(filename)[:-4]
                filepath = os.path.abspath(filename)
        return self.testnames

    def columnCount(self, index):
        pass

Another question is how can I load an html page (in a qwebview) associated with an item selected from my listview?

Thanking you!!


I think you are misunderstanding the purpose of the data method in the Model classes in Qt. Instead of reloading your data (in your case your list of file names), the data method should be mapping an index given by the associated QListView to an item in your testnames list. For example,

def data(self, index, role):
    if role == Qt.DisplayRole:
        testname = self.testnames[index.row()]
        return testname

It looks like you want your load_docfiles method to store a list of file names in self.testnames. You could rewrite it like this:

def load_docfiles(self):
    cfg = Config()
    for filename in glob.glob(os.path.join(cfg.test_path, 'test_*.rst')):
        self.testnames.append(os.path.basename(filename)[5:-4])
        filepath = os.path.abspath(filename)
        print "load docfile", str(self.testnames)

Your class could then be called from your main application like this:

self.view = QtGui.QListView(self)
self.model = TestListModel()
self.model.load_docfiles()
self.view.setModel(self.model)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜