USB Storage detection and file read/write.

  • Hi,
    I want to detect pen drive plugin in Qt application and file read/write to it.
    Please let suggest me about it. I am using Qt4.8.

  • Moderators

    @Awadhesh-Maurya Which OS are you targetting ? If Linux and if it has UDisks daemon running then use qdbus. Check this blog for more info.

  • Lifetime Qt Champion


    To stay cross-platform your can consider the use of KDE's Solid library

    Hope it helps

  • @SGaist , do you know if the kde solid library is something I can use if I am planning to deploy to mac, windows and linux?

  • Lifetime Qt Champion

    Yes it is

  • I was able to use a timer to keep looking at QDir::drives() to check for changes in the list. Works on Windows 7; I am making no claims for other platforms. Here's some code:

    I call initFileSystem() from elsewhere initially.

    void MyWidget::initFileSystem()
      if (mFileSystemModel)
        delete mFileSystemModel;
      mFileSystemModel = new QFileSystemModel(qApp);
      initListView(true);  // this just clears the view and sets its root to match the file model
      if ( !mDriveWatcherInitialized )
    void MyWidget::initDriveWatcher()
      bool connected = true;
      mDriveWatcherTimer = new QTimer(this);
      mDriveWatcherTimer->setInterval(DRIVE_WATCHER_TIMER_MILLISECONDS);  // e.g. 300 - 500 ms
      connected &= connect(mDriveWatcherTimer, SIGNAL(timeout()), this, SLOT(checkForDriveChanges())) != nullptr;
      mDriveWatcherInitialized = true;
    void MyWidget::checkForDriveChanges()
      // skip on/near startup
      static const int NUM_TIMES_TO_SKIP_DRIVE_CHANGE_CHECK = 5;
      static int timesThrough = 0;
      if (timesThrough++ < NUM_TIMES_TO_SKIP_DRIVE_CHANGE_CHECK)
      static QFileInfoList originalFileInfoList = QDir::drives();
      QFileInfoList currentFileInfoList = QDir::drives();
      bool drivesChanged = false;
      // quick easy check
      if (currentFileInfoList.size() != originalFileInfoList.size())
        drivesChanged = true;
        // harder brute force check
        int numMatches = 0;
        foreach(QFileInfo currentFileInfo, currentFileInfoList)
          foreach(QFileInfo originalFileInfo, originalFileInfoList)
            if (currentFileInfo.absolutePath() == originalFileInfo.absolutePath())
          }  // foreach(QFileInfo originalFileInfo, originalFileInfoList)
        }  // foreach(QFileInfo currentFileInfo, currentFileInfoList)
        if (numMatches != currentFileInfoList.size())
          drivesChanged = true;
      }  // else
      if (drivesChanged)
        initFileSystem();  // this is what kicks the model
        originalFileInfoList = QDir::drives();
    }  // void MyWidget::checkForDriveChanges()

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.