How to filter files in qlistview python












1















I am trying to filter elements in listview from the dropdown option user selected. Here is my code so far.



class DirectoryView(QWidget):
def __init__(self):
super().__init__()
self.layout = QHBoxLayout(self)
self.listview = QListView()
self.layout.addWidget(self.listview)
self.setAcceptDrops(True)
self.listview.setSelectionMode(
QtWidgets.QAbstractItemView.ExtendedSelection
)
self.fileModel = QFileSystemModel()
self.listview.setModel(self.fileModel)
self.cb = QComboBox()
self.layout.addWidget(self.cb)
self.cb.currentTextChanged.connect(self.filterClicked)
self.cb.addItem(".mp4")
self.cb.addItem(".gif")

def dragEnterEvent(self, e):
e.accept()

def dropEvent(self, e):
if e.mimeData().hasUrls():
e.accept()
for url in e.mimeData().urls():
print(url)
fname = str(url.toLocalFile())
self.updateDirectoryView(fname)

def updateDirectoryView(self,path):
self.listview.setRootIndex(self.fileModel.setRootPath(path))

def filterClicked(self):
print("todo")


I want to filter elements when user change option of the dropdown.










share|improve this question





























    1















    I am trying to filter elements in listview from the dropdown option user selected. Here is my code so far.



    class DirectoryView(QWidget):
    def __init__(self):
    super().__init__()
    self.layout = QHBoxLayout(self)
    self.listview = QListView()
    self.layout.addWidget(self.listview)
    self.setAcceptDrops(True)
    self.listview.setSelectionMode(
    QtWidgets.QAbstractItemView.ExtendedSelection
    )
    self.fileModel = QFileSystemModel()
    self.listview.setModel(self.fileModel)
    self.cb = QComboBox()
    self.layout.addWidget(self.cb)
    self.cb.currentTextChanged.connect(self.filterClicked)
    self.cb.addItem(".mp4")
    self.cb.addItem(".gif")

    def dragEnterEvent(self, e):
    e.accept()

    def dropEvent(self, e):
    if e.mimeData().hasUrls():
    e.accept()
    for url in e.mimeData().urls():
    print(url)
    fname = str(url.toLocalFile())
    self.updateDirectoryView(fname)

    def updateDirectoryView(self,path):
    self.listview.setRootIndex(self.fileModel.setRootPath(path))

    def filterClicked(self):
    print("todo")


    I want to filter elements when user change option of the dropdown.










    share|improve this question



























      1












      1








      1








      I am trying to filter elements in listview from the dropdown option user selected. Here is my code so far.



      class DirectoryView(QWidget):
      def __init__(self):
      super().__init__()
      self.layout = QHBoxLayout(self)
      self.listview = QListView()
      self.layout.addWidget(self.listview)
      self.setAcceptDrops(True)
      self.listview.setSelectionMode(
      QtWidgets.QAbstractItemView.ExtendedSelection
      )
      self.fileModel = QFileSystemModel()
      self.listview.setModel(self.fileModel)
      self.cb = QComboBox()
      self.layout.addWidget(self.cb)
      self.cb.currentTextChanged.connect(self.filterClicked)
      self.cb.addItem(".mp4")
      self.cb.addItem(".gif")

      def dragEnterEvent(self, e):
      e.accept()

      def dropEvent(self, e):
      if e.mimeData().hasUrls():
      e.accept()
      for url in e.mimeData().urls():
      print(url)
      fname = str(url.toLocalFile())
      self.updateDirectoryView(fname)

      def updateDirectoryView(self,path):
      self.listview.setRootIndex(self.fileModel.setRootPath(path))

      def filterClicked(self):
      print("todo")


      I want to filter elements when user change option of the dropdown.










      share|improve this question
















      I am trying to filter elements in listview from the dropdown option user selected. Here is my code so far.



      class DirectoryView(QWidget):
      def __init__(self):
      super().__init__()
      self.layout = QHBoxLayout(self)
      self.listview = QListView()
      self.layout.addWidget(self.listview)
      self.setAcceptDrops(True)
      self.listview.setSelectionMode(
      QtWidgets.QAbstractItemView.ExtendedSelection
      )
      self.fileModel = QFileSystemModel()
      self.listview.setModel(self.fileModel)
      self.cb = QComboBox()
      self.layout.addWidget(self.cb)
      self.cb.currentTextChanged.connect(self.filterClicked)
      self.cb.addItem(".mp4")
      self.cb.addItem(".gif")

      def dragEnterEvent(self, e):
      e.accept()

      def dropEvent(self, e):
      if e.mimeData().hasUrls():
      e.accept()
      for url in e.mimeData().urls():
      print(url)
      fname = str(url.toLocalFile())
      self.updateDirectoryView(fname)

      def updateDirectoryView(self,path):
      self.listview.setRootIndex(self.fileModel.setRootPath(path))

      def filterClicked(self):
      print("todo")


      I want to filter elements when user change option of the dropdown.







      python python-3.x pyqt pyqt5 qfilesystemmodel






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 0:08









      eyllanesc

      83.7k103562




      83.7k103562










      asked Nov 25 '18 at 23:48









      Abdul AhadAbdul Ahad

      346




      346
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You have to use setNameFilters() and pass a list of wildcards in addition set False to nameFilterDisables:



          from PyQt5 import QtCore, QtGui, QtWidgets

          class DirectoryView(QtWidgets.QWidget):
          def __init__(self):
          super().__init__()
          self.setAcceptDrops(True)

          self.listview = QtWidgets.QListView()
          self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
          self.fileModel = QtWidgets.QFileSystemModel(nameFilterDisables=False)
          self.listview.setModel(self.fileModel)

          self.cb = QtWidgets.QComboBox()
          self.cb.currentTextChanged.connect(self.filterChanged)

          layout = QtWidgets.QHBoxLayout(self)
          layout.addWidget(self.listview)
          layout.addWidget(self.cb)

          def dragEnterEvent(self, e):
          e.accept()

          def dropEvent(self, e):
          if e.mimeData().hasUrls():
          e.accept()
          for url in e.mimeData().urls():
          if url.isLocalFile():
          if self.updateDirectoryView(url.toLocalFile()):
          break

          def updateDirectoryView(self, path):
          fi = QtCore.QFileInfo(path)
          if fi.isDir():
          self.listview.setRootIndex(self.fileModel.setRootPath(path))
          d = QtCore.QDir(path)
          suffixes = set()
          for fi in d.entryInfoList(filters=QtCore.QDir.Files):
          if fi.isFile():
          suffixes.add("."+fi.suffix())
          self.cb.clear()
          self.cb.addItems(sorted(suffixes))
          return True
          return False

          @QtCore.pyqtSlot(str)
          def filterChanged(self, text):
          self.fileModel.setNameFilters(["*"+text])

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          w = DirectoryView()
          w.show()
          sys.exit(app.exec_())





          share|improve this answer


























          • That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

            – Abdul Ahad
            Nov 26 '18 at 0:49











          • @AbdulAhad I've already updated my answer with that requirement, try it

            – eyllanesc
            Nov 26 '18 at 1:14











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473157%2fhow-to-filter-files-in-qlistview-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You have to use setNameFilters() and pass a list of wildcards in addition set False to nameFilterDisables:



          from PyQt5 import QtCore, QtGui, QtWidgets

          class DirectoryView(QtWidgets.QWidget):
          def __init__(self):
          super().__init__()
          self.setAcceptDrops(True)

          self.listview = QtWidgets.QListView()
          self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
          self.fileModel = QtWidgets.QFileSystemModel(nameFilterDisables=False)
          self.listview.setModel(self.fileModel)

          self.cb = QtWidgets.QComboBox()
          self.cb.currentTextChanged.connect(self.filterChanged)

          layout = QtWidgets.QHBoxLayout(self)
          layout.addWidget(self.listview)
          layout.addWidget(self.cb)

          def dragEnterEvent(self, e):
          e.accept()

          def dropEvent(self, e):
          if e.mimeData().hasUrls():
          e.accept()
          for url in e.mimeData().urls():
          if url.isLocalFile():
          if self.updateDirectoryView(url.toLocalFile()):
          break

          def updateDirectoryView(self, path):
          fi = QtCore.QFileInfo(path)
          if fi.isDir():
          self.listview.setRootIndex(self.fileModel.setRootPath(path))
          d = QtCore.QDir(path)
          suffixes = set()
          for fi in d.entryInfoList(filters=QtCore.QDir.Files):
          if fi.isFile():
          suffixes.add("."+fi.suffix())
          self.cb.clear()
          self.cb.addItems(sorted(suffixes))
          return True
          return False

          @QtCore.pyqtSlot(str)
          def filterChanged(self, text):
          self.fileModel.setNameFilters(["*"+text])

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          w = DirectoryView()
          w.show()
          sys.exit(app.exec_())





          share|improve this answer


























          • That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

            – Abdul Ahad
            Nov 26 '18 at 0:49











          • @AbdulAhad I've already updated my answer with that requirement, try it

            – eyllanesc
            Nov 26 '18 at 1:14
















          0














          You have to use setNameFilters() and pass a list of wildcards in addition set False to nameFilterDisables:



          from PyQt5 import QtCore, QtGui, QtWidgets

          class DirectoryView(QtWidgets.QWidget):
          def __init__(self):
          super().__init__()
          self.setAcceptDrops(True)

          self.listview = QtWidgets.QListView()
          self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
          self.fileModel = QtWidgets.QFileSystemModel(nameFilterDisables=False)
          self.listview.setModel(self.fileModel)

          self.cb = QtWidgets.QComboBox()
          self.cb.currentTextChanged.connect(self.filterChanged)

          layout = QtWidgets.QHBoxLayout(self)
          layout.addWidget(self.listview)
          layout.addWidget(self.cb)

          def dragEnterEvent(self, e):
          e.accept()

          def dropEvent(self, e):
          if e.mimeData().hasUrls():
          e.accept()
          for url in e.mimeData().urls():
          if url.isLocalFile():
          if self.updateDirectoryView(url.toLocalFile()):
          break

          def updateDirectoryView(self, path):
          fi = QtCore.QFileInfo(path)
          if fi.isDir():
          self.listview.setRootIndex(self.fileModel.setRootPath(path))
          d = QtCore.QDir(path)
          suffixes = set()
          for fi in d.entryInfoList(filters=QtCore.QDir.Files):
          if fi.isFile():
          suffixes.add("."+fi.suffix())
          self.cb.clear()
          self.cb.addItems(sorted(suffixes))
          return True
          return False

          @QtCore.pyqtSlot(str)
          def filterChanged(self, text):
          self.fileModel.setNameFilters(["*"+text])

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          w = DirectoryView()
          w.show()
          sys.exit(app.exec_())





          share|improve this answer


























          • That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

            – Abdul Ahad
            Nov 26 '18 at 0:49











          • @AbdulAhad I've already updated my answer with that requirement, try it

            – eyllanesc
            Nov 26 '18 at 1:14














          0












          0








          0







          You have to use setNameFilters() and pass a list of wildcards in addition set False to nameFilterDisables:



          from PyQt5 import QtCore, QtGui, QtWidgets

          class DirectoryView(QtWidgets.QWidget):
          def __init__(self):
          super().__init__()
          self.setAcceptDrops(True)

          self.listview = QtWidgets.QListView()
          self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
          self.fileModel = QtWidgets.QFileSystemModel(nameFilterDisables=False)
          self.listview.setModel(self.fileModel)

          self.cb = QtWidgets.QComboBox()
          self.cb.currentTextChanged.connect(self.filterChanged)

          layout = QtWidgets.QHBoxLayout(self)
          layout.addWidget(self.listview)
          layout.addWidget(self.cb)

          def dragEnterEvent(self, e):
          e.accept()

          def dropEvent(self, e):
          if e.mimeData().hasUrls():
          e.accept()
          for url in e.mimeData().urls():
          if url.isLocalFile():
          if self.updateDirectoryView(url.toLocalFile()):
          break

          def updateDirectoryView(self, path):
          fi = QtCore.QFileInfo(path)
          if fi.isDir():
          self.listview.setRootIndex(self.fileModel.setRootPath(path))
          d = QtCore.QDir(path)
          suffixes = set()
          for fi in d.entryInfoList(filters=QtCore.QDir.Files):
          if fi.isFile():
          suffixes.add("."+fi.suffix())
          self.cb.clear()
          self.cb.addItems(sorted(suffixes))
          return True
          return False

          @QtCore.pyqtSlot(str)
          def filterChanged(self, text):
          self.fileModel.setNameFilters(["*"+text])

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          w = DirectoryView()
          w.show()
          sys.exit(app.exec_())





          share|improve this answer















          You have to use setNameFilters() and pass a list of wildcards in addition set False to nameFilterDisables:



          from PyQt5 import QtCore, QtGui, QtWidgets

          class DirectoryView(QtWidgets.QWidget):
          def __init__(self):
          super().__init__()
          self.setAcceptDrops(True)

          self.listview = QtWidgets.QListView()
          self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
          self.fileModel = QtWidgets.QFileSystemModel(nameFilterDisables=False)
          self.listview.setModel(self.fileModel)

          self.cb = QtWidgets.QComboBox()
          self.cb.currentTextChanged.connect(self.filterChanged)

          layout = QtWidgets.QHBoxLayout(self)
          layout.addWidget(self.listview)
          layout.addWidget(self.cb)

          def dragEnterEvent(self, e):
          e.accept()

          def dropEvent(self, e):
          if e.mimeData().hasUrls():
          e.accept()
          for url in e.mimeData().urls():
          if url.isLocalFile():
          if self.updateDirectoryView(url.toLocalFile()):
          break

          def updateDirectoryView(self, path):
          fi = QtCore.QFileInfo(path)
          if fi.isDir():
          self.listview.setRootIndex(self.fileModel.setRootPath(path))
          d = QtCore.QDir(path)
          suffixes = set()
          for fi in d.entryInfoList(filters=QtCore.QDir.Files):
          if fi.isFile():
          suffixes.add("."+fi.suffix())
          self.cb.clear()
          self.cb.addItems(sorted(suffixes))
          return True
          return False

          @QtCore.pyqtSlot(str)
          def filterChanged(self, text):
          self.fileModel.setNameFilters(["*"+text])

          if __name__ == '__main__':
          import sys
          app = QtWidgets.QApplication(sys.argv)
          w = DirectoryView()
          w.show()
          sys.exit(app.exec_())






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 26 '18 at 1:12

























          answered Nov 26 '18 at 0:07









          eyllanesceyllanesc

          83.7k103562




          83.7k103562













          • That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

            – Abdul Ahad
            Nov 26 '18 at 0:49











          • @AbdulAhad I've already updated my answer with that requirement, try it

            – eyllanesc
            Nov 26 '18 at 1:14



















          • That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

            – Abdul Ahad
            Nov 26 '18 at 0:49











          • @AbdulAhad I've already updated my answer with that requirement, try it

            – eyllanesc
            Nov 26 '18 at 1:14

















          That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

          – Abdul Ahad
          Nov 26 '18 at 0:49





          That works perfectly. One more thing. How can I add items (extensions) to combo box that are in directory?

          – Abdul Ahad
          Nov 26 '18 at 0:49













          @AbdulAhad I've already updated my answer with that requirement, try it

          – eyllanesc
          Nov 26 '18 at 1:14





          @AbdulAhad I've already updated my answer with that requirement, try it

          – eyllanesc
          Nov 26 '18 at 1:14




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473157%2fhow-to-filter-files-in-qlistview-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Costa Masnaga

          Fotorealismo

          Sidney Franklin