Qt之QStorageInfo获取磁盘信息

QStorageInfo类提供了系统当前挂载的磁盘的相关信息,包括它们的总大小,盘符名,文件系统名等,具体的可以参考Qt的帮助文档。使用如下:

void MainWindow::SlotGetDiskInfo()
{
    QStorageInfo storage = QStorageInfo::root();
    qDebug() << "storage=======" << storage.rootPath();
    qDebug() << "storage=======" << storage.device();
    QList<QStorageInfo> list = QStorageInfo::mountedVolumes();

    int count = list.size();
    QString strInfo = "";
    for(int i = 0; i < count; ++i)
    {
        QStorageInfo diskInfo = list.at(i);
        qint64 freeSize = diskInfo.bytesFree();
        qint64 totalSize = diskInfo.bytesTotal();
        QString tempInfo = QString("name:%1     totalSize:%2    freeSize:%3 \n").arg(diskInfo.displayName()).arg(GetStorageSize(totalSize)).arg(GetStorageSize(freeSize));
        strInfo.append(tempInfo);
    }
    ui->textEdit->setText(strInfo);
}

QString MainWindow::GetStorageSize(qint64 size)
{
    if(size < 1024)
    {
        return QString("%1 B").arg(size);
    }
    else
    {
        size = size / 1024;
    }

    double tempSize = 1.0 * size;
    if(tempSize < 1024)
    {
        return QString("%1 KB").arg(tempSize);
    }
    else
    {
        tempSize = tempSize / 1024;
    }

    if(tempSize < 1024)
    {
        return QString("%1 MB").arg(tempSize);
    }
    else
    {
        tempSize = tempSize / 1024;
    }
    if(tempSize < 1024)
    {
        return QString("%1 GB").arg(tempSize);
    }
    else
    {
        tempSize = tempSize / 1024;
    }

    return "";
}

Qt之QStorageInfo获取磁盘信息