Search code examples
pyqtqcomboboxqfilesystemmodel

populating combo box with folders on disk using QFileSystemModel


Hi I have written this basic code trying to populate folders underneath the /Users/ directory, but I don't know what I am missing its not populating.

import sys

from PyQt4 import QtGui 
from PyQt4 import QtCore


class MyWindow(QtGui.QWidget):
    """docstring for MyWindow"""
    def __init__(self, parent=None):
        super(MyWindow, self).__init__()
        self.setup()

    def setup(self):
        fsm = QtGui.QFileSystemModel()
        fsm.setRootPath("/Users/")
        layout = QtGui.QVBoxLayout()
        combo = QtGui.QComboBox()
        combo.setModel(fsm)
        layout.addWidget(combo)
        self.setLayout(layout)



def main():
    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    win.show()
    win.raise_()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

I am getting a / in the comobobox instead of the whole list of folders under /Users/ directory.

I think its better to use QFileSystemModel instead of using os.listdir interms of efficiency and will update the view if somebody updates folder or adds folder in the /Users/ directory !


Solution

  • Remember that QFileSystemModel is a hierarchical model, so you need to let the QComboBox know which QModelIndex represents the children you want to display. You do that with QComboBox.setRootModelIndex()

    QFileSystemModel.setRootPath() conveniently returns the QModelIndex of the path you set.

    So a small change is all you need (tested on Windows) -

    import sys
    
    from PyQt4 import QtGui 
    from PyQt4 import QtCore
    
    
    class MyWindow(QtGui.QWidget):
        """docstring for MyWindow"""
        def __init__(self, parent=None):
            super(MyWindow, self).__init__()
            self.setup()
    
        def setup(self):
            fsm = QtGui.QFileSystemModel()
            index = fsm.setRootPath("/Users/")
            layout = QtGui.QVBoxLayout()
            combo = QtGui.QComboBox()
            combo.setModel(fsm)
            combo.setRootModelIndex(index)
            layout.addWidget(combo)
            self.setLayout(layout)
    
    def main():
        app = QtGui.QApplication(sys.argv)
        win = MyWindow()
        win.show()
        win.raise_()
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
        main()