3

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 !

Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197

1 Answers1

5

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()
Tim Wakeham
  • 1,029
  • 1
  • 8
  • 12