Pyside, PyQt, QFileSystemModel: how to detect adding/removing a drive and update the QTreeView
-
Using the following code, my model and view works fine with it.
@
self.dirModel = QFileSystemModel()
self.dirModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
self.dirModel.setRootPath(self.dirModel.myComputer())
self.sourceTreeView.clicked.connect(self.sourceTreeViewClicked)
self.sourceTreeView.setModel(self.dirModel)
@How can i make QFileSystemModel to detect a new drive when i insert my USB-Stick?
[edit: added missing coding tags @ SGaist]
-
Hi and welcome to devnet,
What OS/Qt combo are you running ?
Note that QFileSystemModel is not meant to this kind of detection.
-
The simplest way to do it is to create your own watcher object and have that reload the QFileSystemModel when something changes. The following basic example is for Windows and does just that (it depends on the pywin32 binding BTW):
@
import sip
sip.setapi('QString',2)
sip.setapi('QVariant',2)from PyQt4.QtCore import *
from PyQt4.QtGui import *from win32com.client import Dispatch
class DriveWatcher(QObject):
driveCountChanged=pyqtSignal()def __init__(self, parent=None, **kwargs): QObject.__init__(self, parent, **kwargs) self._drives={} self.getDrives() def getDrives(self): drives={} for d in Dispatch("Scripting.FileSystemObject").Drives: drives[d.DriveLetter]=d.VolumeName added=set(drives.keys())-set(self._drives.keys()) removed=set(self._drives.keys())-set(drives.keys()) self._drives=drives if len(added) or len(removed): self.driveCountChanged.emit() QTimer.singleShot(1000, self.getDrives)
class Widget(QWidget):
def init(self, parent=None, **kwargs):
QWidget.init(self, parent, **kwargs)l=QVBoxLayout(self) self._fmodel=None self._fview=QTableView(self) l.addWidget(self._fview) self._watcher=DriveWatcher(self, driveCountChanged=self.driveCountChanged) @pyqtSlot() def driveCountChanged(self): if self._fmodel: del self._fmodel self._fmodel=QFileSystemModel(self) self._fmodel.setRootPath(self._fmodel.myComputer()) self._fview.setModel(self._fmodel)
if name=="main":
from sys import argv, exita=QApplication(argv) w=Widget() w.show() w.raise_() exit(a.exec_())
@
Hope this helps ;o)
-
Thank you guys for your answers. I use Windows 7 with Python 2.7.6 and Pyside as Qt-Python bindings. But i also like to test it on a Debian or openSUSE Linux. I read in the API guide to use QFileSystemModel instead of deprecated QDirModel. If i use
@self.dirModel = QDirModel()
self.sourceTreeView.setModel(self.dirModel)@in my code, the TreeView gets automatic updated when i insert/remove my USB-Stick. I thought i can have that behavior also with QFileSystemModel() in some configuration.
So what is the best way to detect an insert/remove of an USB-Stick on Windows and Linux using Pyside Qt bindings?